Miller Rabin is undoubtedly the most popular probabilistic primality testing algorithm.
It uses the concept of Fermat’s Little Theorem.So if you don’t know fermat’s little theorem,it is advised to understand it first – Fermat
Let us Begin.
For an odd prime number p, we can write
Here s is odd and d>=1
By Fermat’s Little Theorem,we can write –
Thus for p to be prime , at least one of the terms in the expansion should be divisible by p.
In other words,
If none of the conditions are true then p is definitely composite, otherwise p maybe prime.
To increase the accuracy of the algorithm, we will perform the check for certain number of iterations for some random values of a lesser than p.
Here’s the python implementation –
The Algorithm is slower than Fermat’s Little primality test but is still preferred due to it’s high accuracy.
NOTE – If you are implementing the algorithm in C/C++ , take care of the overflows while multiplying two long long ints in modular exponentiation.
Try out this problem on SPOJ/PON
For any queries,drop a comment below 🙂