Here is the question
Find all Pythagorean Triples for side1, side2 and hypotenuse all no longer than 500. Use a triple nested for loops that tries possibilities.
The below is my attempt
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int side1 = 0;
int side2 = 0;
int rightSide = 0;
cout << "Right Side" << setw(10) << "Side1" << setw(10) << "Side2" << endl;
for(int i=1;i<=500;i++)
{
side1++;
//cout << side1 << endl;
for(int a=1;a<=500;a++)
{
side2++;
//cout << "side 2 " << side2 << endl;
for(int c=1;c<=500;c++)
{
rightSide++;
int rightSideSqr = rightSide*rightSide;
int side1Sqr = side1*side1;
int side2Sqr = side2*side2;
if(rightSideSqr == side1Sqr+side2Sqr)
{
cout << rightSideSqr << setw(15) << side1 << setw(10) << side2 << endl;
}
}
}
}
}
But it gives no success, seems like an infinite loop. Please help.
Please Note: I am new to C++, I study it by my self. And, this is not an homework, I made the problem statement because it is the best way to express the issue.
EDIT
Right Side Side1 Side2
RUN SUCCESSFUL (total time: 1s)
EDIT 2
Working code
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
//int side1 = 0;
//int side2 = 0;
//int rightSide = 0;
cout << "Right Side" << setw(10) << "Side1" << setw(10) << "Side2" << endl;
for(int i=1;i<=500;i++)
{
//side1++;
//cout << side1 << endl;
for(int a=1;a<=500;a++)
{
//side2++;
//cout << "side 2 " << side2 << endl;
for(int c=1;c<=500;c++)
{
//rightSide++;
int rightSideSqr = c*c;
int side1Sqr = i*i;
int side2Sqr = a*a;
if(rightSideSqr == (side1Sqr+side2Sqr))
{
cout << rightSideSqr << setw(15) << i << setw(10) << a << endl;
}
}
}
}
}
It’s not an infinite loop, it’s just a very slow finite loop. I/O is slow — you’re printing out 500*500 = 250,000 lines of text in the
coutstatement in the middle loop, and printing out 250,000 lines of text to the console is very, very slow. If you remove that print statement, it will execute much more quickly.Secondly, you have an error in your logic. The variables
side1,side2, andrightSidenever get reset to 0 at the appropriate times, so they just keep incrementing beyond their intended values. Try resetting them to 0, or just use the loop counters instead of extra variables like that.