A little while back, I posted some code implementing the Miller-Rabin primality test and compared it vs. the Naive primality test (you can read that article here). The results were rather staggering for semi-large numbers. However, I did make the comment that 32-bits really isn't that big.

So, in keeping of the spirit of cocking about I took that code and implemented it to use BigIntegers :D

Now, there's no way I'm going to even try to run a naive algorithm against this algorithm in the range I had in mind, so I decided to compare it against Java's BigInteger built-in primality test :D If I'm guessing correctly, is implemented using the Solovay-Strassen test.

Yeah, that right :D I tried it with numbers containing 1024 bits. To get a sense of the scale, the numbers I'm checking primality for are ~17e308. That's over 200 orders of magnitude larger than a google!

So how did these two methods fair?

Surprisingly, both methods came out with roughly the same execution time. This is because in practice the accuracy of these primality tests only require ~1-2 iteration to determine if a number is composite. Also, the majority of the time spent in both methods are doing basic math on these huge numbers (particularly multiplication, exponentiation, division, and modulo operations), which will dominate the test time. It's only the worst-case scenario where the Miller-Rabin test can give you the same certainty percentage at O(n) iterations vs. O(n^2) iterations, which rarely happens for either test.

However, I did find that the Miller-Rabin test was marginally faster (~1-2 seconds on average), as well as being more stable (the time taken between runs had a smaller standard deviation). Here were my outputs (times are in milliseconds):

There were no differences output-wise between the two tests in terms of determining if a number was prime or composite.

So what now? Where else can speed be improved on? Honestly, the only potential place for major improvements I can think of is inside the BigInteger class. I'm not sure how it implements many of it's arithmetic operations, though if multiplication, division, modulo, and exponentiation are not implemented using a FFT (or similar method), there's 1 order of magnitude that could be improved. However, I don't think I'm going to go about writing my own BigInteger class for Java (at least not any time soon).

You're free to use this code anywhere you want, though I'm not responsible for any problems it may have. I would like to here about any problems, though. Maybe I'll get around to fixing them.