I wrote a small program to calculate the first 18 triples (x,y,z) with x<y<z that satisfy x^3+y^3=z^3+1 .
During the game, to optimize the overall execution time, I found that using double for cubic values โโand two sides of the equation is faster than using long . On my car, the difference is about 3 seconds.
Now I wonder why that is. I suppose this is somewhere in the internal processing of long , while comparing the two long Variables, since this is the only thing that changes in the calculation loops.
Here is my code:
class Threes { public static void main(String[] args) { System.out.println("Threes --- Java"); int Z_MAX = 60000, Y_MAX = Z_MAX-1, X_MAX = Y_MAX-1; double[] powers = new double[Z_MAX+1]; for (int i = 0; i <= Z_MAX; i++) { powers[i] = Math.pow(i, 3); } System.out.println("Powers calculated"); int x, y, z; double right, left; int[][] sets = new int[18][3]; int foundCount = 0; long loopCount = 0; long start, end; start = System.currentTimeMillis(); for (x = 1 ; x < X_MAX; x++) { for (y = x + 1; y < Y_MAX; y++) { right = powers[x] + powers[y]; for (z = y + 1; z < Z_MAX; z++) { left = powers[z] + 1; if (right < left) { z = Z_MAX; } else if (right == left) { sets[foundCount][0] = x; sets[foundCount][1] = y; sets[foundCount][2] = z; foundCount++; end = System.currentTimeMillis(); System.out.println("found " + foundCount + ". set:\t" + x + "\t" + y + "\t" + z + "\t" + ((end - start) / 1000.0)); if (foundCount == 18) { x = X_MAX; y = Y_MAX; z = Z_MAX; } } loopCount++; } } } System.out.println("finished: " + loopCount); } }
I changed the following lines:
double[] powers = new double[Z_MAX+1];
becomes
long[] powers = new long[Z_MAX+1];
and
powers[i] = Math.pow(i, 3);
becomes
powers[i] = (long)Math.pow(i, 3);
and
double right, left;
becomes
long right, left;
Bonus Question: What other possibilities do I have for optimizing the entire code in terms of the total duration of work? I know that to leave loopCount me a few milliseconds. I am sure that I need to significantly reduce the number of loop iterations. But how?