/*5.20 (Pythagorean Triples) A right triangle can have sides whose
lengths are all integers. The set of three integer values for the
lengths of the sides of a right triangle is called a Pythagorean
triple. The lengths of the three sides must satisfy the relationship
that the sum of the squares of two of the sides is equal to the
square of the hypotenuse. Write an application that displays a
table of the Pythagorean triples for , and the
, all no larger than 500. Use a triple-nested loop
that tries all possibilities. This is an example of “brute-force”
computing. You’ll learn in more advanced computer-science
courses that for many interesting problems there’s no known
algorithmic approach other than using sheer brute force*/
//Luis Fernando
#include <iostream>
using std::cout;
using std::endl;
#include <math.h>
int main(int argc, char** argv)
{
cout << "pythagorean triples" << endl;
for(int side1 = 1; side1 < 500; side1 ++)
{
for(int side2 = 1; side2 < 500; side2 ++)
{
for(int hypotenuse = 1; hypotenuse < 500; hypotenuse ++)
{
//take a range between 1 to 500 as a result
if(pow(side1,2) + pow(side2,2) == pow(hypotenuse,2) && pow(hipotenusa,2) <= 500)
{
cout << side1 << " + " << side2 << " = " << hypotenuse << endl;
}
}
}
}
return 0;
}
#include <iostream>
int main()
{
constint UBOUND = 501 ; // no larger than 500
int cnt = 0 ;
// Use a triple-nested loop that tries all possibilities (brute force).
// let a, b, c be the three sides such that a<b and a*a + b*b == c*c
for( int a = 1 ; a < UBOUND ; ++a )
{
constint aa = a*a ;
for( int b = a+1 ; b < UBOUND ; ++b ) // for b > a
{
constint bb = b*b ;
constint sum = aa + bb ; // sum of squares of the two smaller sides
for( int c = b+1 ; c < UBOUND ; ++c ) // c must be greater than b
{
constint cc = c*c ; // square of the largest side
if( sum == cc ) // found a pythagorean triplet, print it
{
std::cout << ++cnt << ". ( " << a << ", " << b << ", " << c << " )\n" ;
}
if( cc >= sum ) break ; // no point in checking for higher values of c
}
}
}
}
#include <iostream>
#include <set>
usingnamespace std;
int main()
{
constint UBOUND = 500;
set<int> squares;
// Precompute perfect squares
for ( int i = 1; i <= UBOUND; i++ ) squares.insert( i * i );
auto first = squares.begin();
int ccmax = UBOUND * UBOUND;
// Search for pairs aa and bb such that aa + bb is in squares.
for ( auto aa = first; aa != squares.end(); aa++ )
{
for ( auto bb = aa; bb != squares.end() && *aa + *bb <= ccmax; bb++ )
{
auto cc = squares.find( *aa + *bb );
if ( cc != squares.end() )
{
cout << distance( first, aa ) + 1 << '\t'
<< distance( first, bb ) + 1 << '\t'
<< distance( first, cc ) + 1 << '\n';
}
}
}
}