I'm currently working my way through a book on simple optimizations. One of the algorithms shown was:
Print all solutions to a3 + b3 = c3 + d3 (where a, b, c, d are less than 1000)
(I went with 100 so it would run quicker on my slow netbook)
I programmed up their solution (Their solution and their first offered optimisation are included), however the break optimisation offered actually made the algorithm a fair bit slower.
public static void doUnoptimised() {
for(int a = 1; a < 100; a++)
{
for(int b = 1; b < 100; b++)
{
for(int c = 1; c < 100; c++)
{
for(int d = 1; d < 100; d++) {
if(Math.pow(a, 3) + Math.pow(b, 3) == Math.pow(c, 3) + Math.pow(d, 3))
{
System.out.println("A:" + a + " B:" + b + " C:" + c + " D:" + d);
}
}
}
}
}
}
public static void doFirstOptimised() {
for(int a = 1; a < 100; a++)
{
for(int b = 1; b < 100; b++)
{
for(int c = 1; c < 100; c++)
{
for(int d = 1; d < 100; d++) {
if(Math.pow(a, 3) + Math.pow(b, 3) == Math.pow(c, 3) + Math.pow(d, 3))
{
System.out.println("A:" + a + " B:" + b + " C:" + c + " D:" + d);
break;
}
}
}
}
}
}
Why is that? Note that this isn't my solution, this is the one shown in the book, and they go on with more optimizations later but I'm interested in why this optimization was such an epic fail.
Edit - Perhaps I'm not being clear enough here. I know this is a barely noticeable change and I understand why this is an improvement and have already gone through the better optimizations offered in the book. (Thanks for those giving better optimisations though, appreciate the effort) However this particular step one does not work at all and im trying to figure out why. But at this stage it seems like my jvm is just weird.