We\'re having a bit of fun here at work. It all started with one of the guys setting up a Hackintosh and we were wondering whether it was faster than a Windows Box of (nearl
Well I see a couple of quick optimizations that can be done. First you don't have to try each number up to half of the current number.
Instead you only have try up to the square root of the current number.
And the other optimization was what BP said with a twist: Instead of
int count = 0;
...
for (int i = 2; i < top; i++)
...
if (current == 2)
current++;
else
current += 2;
use
int count = 1;
...
for (int i = 3; i < top; i += 2)
...
current += 2;
This should speed things up quite a lot.
Edit:
More optimization courtesy of Joe Pineda:
Remove the variable "top".
int count = 1;
...
for (int i = 3; i*i <= current; i += 2)
...
current += 2;
If this optimization indeed increases speed is up to java.
Calculating the square root takes a lot of time compared to multiplying two numbers. However since we move the multiplication into the for loop this is done every single loop. So this COULD slow things down depending on how fast the square root algorithm in java is.