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 (nearly) same specs that we have. So we decided to write a little test for it. Just a simple Prime number calculator. It’s written in Java and tells us the time it takes to calculate the first n Prime numbers.
Optimised version below – now takes ~6.6secs
public class Primes { public static void main(String[] args) { int topPrime = 150000; int current = 2; int count = 0; int lastPrime = 2; long start = System.currentTimeMillis(); while (count < topPrime) { boolean prime = true; int top = (int)Math.sqrt(current) + 1; for (int i = 2; i < top; i++) { if (current % i == 0) { prime = false; break; } } if (prime) { count++; lastPrime = current; } if (current == 2) { current++; } else { current = current + 2; } } System.out.println('Last prime = ' + lastPrime); System.out.println('Total time = ' + (double)(System.currentTimeMillis() - start) / 1000); } }
We’ve pretty much lost the plot of the whole Hackintosh vs PC thing and are just having some fun with optimising it. First attempt with no optimisations (the above code has a couple) ran around 52.6min to find the first 150000 prime numbers. This optimisation is running around 47.2mins.
If you want to have a go and post your results, then stick em up.
Specs for the PC I’m running it on are Pentium D 2.8GHz, 2GB RAM, running Ubuntu 8.04.
Best Optimisation so far has been the square root of current, first mentioned by Jason Z.
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
use
This should speed things up quite a lot.
Edit:
More optimization courtesy of Joe Pineda:
Remove the variable ‘top’.
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.