I made a program that returns the product abc where a,b,c are pythagorean triples and add up to 1000. The program does output the correct answer but does it twice. I was curious as to why this is so. After playing around with it a bit I found out that it prints out when a = 200 b = 375 c = 425. And once again when a = 375 b = 200 c = 425.
bool isPythagTriple(int a, int b, int c);
int main()
{
for(int a = 1; a < 1000; a++)
{
for(int b = 1; b < 1000; b++)
{
for(int c = 1; c < 1000; c++)
{
if( ((a+b+c)==1000) && isPythagTriple(a,b,c) )
{
cout << a*b*c << " ";
break;
}
}
}
}
return 0;
}
bool isPythagTriple(int a, int b, int c)
{
if( (a*a)+(b*b)-(c*c) == 0 )
return true;
else
return false;
}
Break, in this case, will only break out of the
cloop, not thebandaones.A quick fix is to ensure you don’t get repeats by starting each variable greater than or equal to the previous (so
bis never less thanaandcis never less thanb).In addition, you can actually get rid of the
cloop altogether since there’s only one value ofcthat is valid for a givena,bpair (unlessa + b + c > 1000in which case there are none). I would try something like:The overall effect of that is to reduce the total loop count from a billion (short scale) to about half a million hence reducing it by about 99.95% – that should be a tiny bit faster 🙂
And potentially making it faster with Jerry Coffin’s suggestion as well (and an inline suggestion to the compiler), a full program:
which takes 0.004 seconds on average (system + user) on my box, with the original taking about 2.772 seconds on average (ten samples each). Not that it really matters unless you’re running it many, many times, of course.
The output of that code is, as expected: