/* * pythagorean.c | Jim Mahoney | Aug 2018 * projecteuler.net #9 ; overflow example from "Computer Systems" text * * $ gcc pythagorean.c -o pythagorean ; ./pythagorean * sum = 1000 : a=200, b=375, c=425 * * So far so good. * * Changing the "int sum = 1000;" line to make the sum bigger, * recompiling and rerunning gives these results: * * sum = 10000 : a=2000, b=3750, c=4250 * sum = 100000 : a=5408, b=69844, c=24748 b > c ??? OOPS!! * * The last result is clearly incorrect, since b is bigger than c. * But the code compiled and ran without warnings or errors. * * Your mission : explain what's going on, in detail. * * Answer : It's all about integer sizes and overflow. * And the result will depend on your C compiler settings. * The printf() statements below illustrate the issue. * */ #include #include int main(){ int a, b, c; int sum = 100000; printf("sizeof(int) == %lu ; max is %lu \n", sizeof(int), (1lu << (8*sizeof(int)-1))-1); printf("sizeof(long int) == %lu ; max is %lu \n", sizeof(long int), (1lu << (8*sizeof(long int)-1))-1); printf("- - - - - - - - - - - \n"); printf("Looking for a,b,c such that a**2+b**2=c**2 and a+b+c=%i ...\n", sum); for (a = 1; a < sum - 2; a++){ for (b = a+1; b < sum - 2; b++){ c = sum - a - b; if (a*a + b*b == c*c){ printf("a = %i, b = %i, c = %i \n", a, b, c); printf(" a * a = %i \n", a*a); printf(" b * b = %i \n", b*b); printf(" c * c = %i \n", c*c); return 0; } } } printf("no solution found.\n"); return 0; }