Pythagorean Triples Program and I can't tell if I have a Infinite Loop?

Hello eveyone. I am trying to find all Pythagorean triples for side1, side2, and hypotenuse all no larger than 500 using brute force computing. I have to use nested for loops and counter-controlled repetition. I have my code and I can't tell if my CPU is taking forever to process the code or if I have an infinite loop issue. Please take a look at my code and advise. I am also not sure if my assignment for hypotenuseSquared is correct. Any assistance is appreciated.



#include <iostream>

using namespace std;

int main()
{
int count = 0; // Number of triples found
long int hypotenuseSquared; // hypotenuse squared
long int sidesSquared; // Sum of squares of sides

cout << "Side 1\tSide 2\tSide 3" << endl;

// Side1 values range from 1 to 500
for ( int side1 = 1; side1 <= 500; side1++ )
{
// Side2 values range from current side1 to 500
for ( int side2 = side1; side2 <= 500; side2++ )
{
// Hypotenuse values range from current side2 to 500
for ( int hypotenuse = side2; hypotenuse <= 500; hypotenuse++ )
{
// Calculate square of hypotenuse value
hypotenuseSquared = (side1 * side1) + (side2 * side2);

// Calculate sum of squared sides
sidesSquared = (side1 * side1) + (side2 * side2);

// If (hypotenuse)^2 = (side1)^2 + (side2)^2,
// Pythagorean triple
if ( hypotenuseSquared == sidesSquared )
{
// Display triple
cout << side1 << '\t' << side2 << '\t'
<< hypotenuse << '\n';
++count; // Update count
}
}
}
}

// Display total number of triples found
cout << "A total of " << count << " triples were found." << endl;

system ("PAUSE");
return 0;
}
It doesn't seem like an infinite loop; however, you can speed this up by removing the hypotenuse loop and calculating whether a^2+b^2 is a perfect square. Oh and you're setting hypotenuseSquared to the same thing as sidesSquared.
What firefly431 was saying is simple these three lines...

hypotenuseSquared = (side1 * side1) + (side2 * side2);

sidesSquared = (side1 * side1) + (side2 * side2);

if ( hypotenuseSquared == sidesSquared )

The if statement will ALWAYS be true.
Last edited on
Thanks for the help my friends. I got it working now.
Topic archived. No new replies allowed.