Here are 5 solutions (from slow to fast):
1) Trivial implementation - 732857 microseconds (0.7 seconds)
private static void p1(int sum) { for (int a = 0; a <= sum; a++) { for (int b = 0; b <= sum; b++) { for (int c = 0; c <= sum; c++) { if (a < b && b < c && a + b + c == sum && (c * c == a * a + b * b)) { System.out.print(a * b * c); return; } } } } }
2) Limit the lower limit for b and c (set the order relation) to 251091 microseconds (0.2 seconds)
private static void p2(int sum) { for (int a = 0; a <= sum; a++) { for (int b = a + 1; b <= sum; b++) { for (int c = b + 1; c <= sum; c++) { if (a + b + c == sum && (c * c == a * a + b * b)) { System.out.print(a * b * c); return; } } } } }
3) Limit the lower and upper bounds for b and c - 111220 microseconds (0.1 seconds)
private static void p3(int sum) { for (int a = 0; a <= sum; a++) { for (int b = a + 1; b <= sum - a; b++) { for (int c = b + 1; c <= sum - a - b; c++) { if (a + b + c == sum && (c * c == a * a + b * b)) { System.out.print(a * b * c); return; } } } } }
4) Limit the lower and upper bounds for b and fix the value for c - 2625 microseconds
private static void p4(int sum) { for (int a = 0; a <= sum; a++) { for (int b = a + 1; b <= sum - a; b++) { int c = sum - a - b; if (c > b && c * c == a * a + b * b) { System.out.print(a * b * c); return; } } } }
5) Use the Euclidean formula - 213 microseconds
private static void p5(int sum) { // a = m^2 - n^2 // b = 2mn // c = m^2 + n^2 int a, b, c; int sqrt = (int)Math.sqrt(sum); for (int n = 1; n <= sqrt; n++) { for (int m = n+1; m <= sqrt; m++) { a = m*m - n*n; b = 2*m*n; c = m*m + n*n; if ( a + b + c == 1000 ) { System.out.print(a * b * c); return; } } } }
ROMANIA_engineer
source share