I’m well aware this brute force method is bad and that I should be using something like Euclid’s formula, and that the final loop isn’t needed as c = 1000 – (a + b) etc… but right now I just want this to work.
bool isPythagorean(int a, int b, int c) {
if((a*a + b*b) == c*c && a < b && b < c) {
cout << a << " " << b << " " << c << endl;
return true;
} else {
return false;
}
}
int main()
{
int a = 1;
int b = 2;
int c = 3;
for(a = 1; a < b; ++a) {
for(b = 2; b < c; ++b) {
for(c = 3; a + b + c != 1000 && !isPythagorean(a, b, c); ++c) {
}
}
}
return 0;
}
For the most part, the code works as I expect it to. I cannot figure out why it is stopping shy of a + b + c = 1000.
My final triplet is 280 < 294 < 406, totalling 980.
If I remove the a < b < c check, the triplet becomes 332, 249, 415 totalling 996.
All results fit the pythagorean theorem — I just cannot land a + b + c = 1000.
What is preventing me?
This part of the code iterates very strangely:
Initially,
a = 1, b = 2, c = 3. But upon the firstfor(c),c=997, so the second iteration offor(b)will run up tob=996. Keep doing this, and at some point you find a triple(a,b,c), at that point,cis probably not close to 1000, b will iterate up to whatever state c was is in… and so on. I don’t think you can accurately predict the way it’s going to come up with triples.I suggest you go with something like
That way, loops won’t depend on the previously found triple.
… and you really should use Euclid’s method.