/* * pythagorean.c | Jim Mahoney | * projecteuler.net #9 * and overflow example from "Computer Systems" text * * $ gcc pythagorean.c -o pythagorean ; ./pythagorean * $ time ./pythagorean * Looking for a,b,c such that a**2+b**2=c**2 and a+b+c=1000 ... * a = 200, b = 375, c = 425 * a * a = 40000 * b * b = 140625 * c * c = 180625 * Looking for a,b,c such that a**2+b**2=c**2 and a+b+c=100000 ... * a = 5408, b = 69844, c = 24748 * a * a = 29246464 * b * b = 583217040 * c * c = 612463504 * - - - - - - - - - - - * An aside on integer sizes : * sizeof(int) == 4 ; max is 2147483647 * sizeof(long int) == 8 ; max is 9223372036854775807 * - - - - - - - - - - - * real 0m1.679s * user 0m1.678s * sys 0m0.000s * * The result for the bigger n is clearly incorrect since b > 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. * */ #include <stdio.h> #include <stdlib.h> #include <limits.h> void search(int sum){ int a, b, c; 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 = %10i \n", a*a); printf(" b * b = %10i \n", b*b); printf(" c * c = %10i \n", c*c); return; } } } printf("no solution found.\n"); } int main(){ search(1000); search(100000); printf("- - - - - - - - - - - \n"); printf("An aside on integer sizes : \n"); printf("sizeof(int) == %lu ; max is %u \n", sizeof(int), INT_MAX); printf("sizeof(long int) == %lu ; max is %lu \n", sizeof(long int), LONG_MAX); printf("- - - - - - - - - - - \n"); return 0; }