Miller Rabin primality test (for 32 bit)
% Remco Bloemen % 2009-11-25, last updated 2014-03-03
As an exercise I implemented the Miller-Rabin primality test in plain C++. It turns out this algorithms lends itself for a true festival of operators, so I couldn’t resist making the code very dense:
bool
That’s it! Now, the algorithm will overflow for n \geq 2^{32} but I intend to use it to find 64-bit primes, so I’ll have to work on that.
Interestingly, the "primes page" claims that (source):
If n < 4759123141 is a 2, 7 and 61-SPRP, then n is prime.
(A number n is called “ k-SPRP” or “strong probable-prime base k ” if it passes Miller Rabin with this k)
Since 4759123141 is greater that 2^{32} we can use this to implement a fast and exact function to determine whether some 32 bit number is prime. I special cased the first several primes to improve performance and made the whole thing into an incomprehensible operator soup, just like the Miller-Rabin implementation:
bool