Miller-Rabin Primality Test
Theorem 1
Let’s express an odd number as . And for all , if there exists a that satisfies the above, then is a composite number.
Explanation
With the increased amount of computation, there’s a possibility to filter out composite numbers that pass the Fermat’s Little Theorem.
For example, a Carmichael number such as , since is , we can quickly verify that is not a prime number. The number used in this judgment, such as , is called a Miller-Rabin Witness. However, even if all pass through the test, it doesn’t mean is a prime.
Proof
Let’s consider an odd prime number as . By Fermat’s Little Theorem,
If not , it might be .
If not even , it might be .
Similarly, at least one of the must be congruent to in or initially, Therefore, if is a prime number, either or at least one of the must Finally, the proof concludes by contraposition.
■
Code
Below is the Miller-Rabin test implemented in R, using the method of successive squaring and Euclidean algorithm for calculation.
FPM<-function(base,power,mod) #It is equal to (base^power)%%mod
{
i<-0
if (power<0) {
while((base*i)%%mod != 1) {i=i+1}
base<-i
power<-(-power)}
if (power==0) {return(1)}
if (power==1) {return(base%%mod)}
n<-0
while(power>=2^n) {n=n+1}
A<-rep(1,n)
A[1]=base
for(i in 1:(n-1)) {A[i+1]=(A[i]^2)%%mod}
for(i in n:1) {
if(power>=2^(i-1)) {power=power-2^(i-1)}
else {A[i]=1} }
for(i in 2:n) {A[1]=(A[1]*A[i])%%mod}
return(A[1])
}
gcd <- function(a, b) {
if (b>a) {i=b; b=a; a=i;}
while(b) {
temp = b
b = a %% b
a = temp
}
return(a)
}
MR.test<-function(n)
{
q=n-1
k=0
while(!q%%2) {q=q/2; k=k+1+6}
for(i in 2:(n-1))
{
if (gcd(i,n)!=1) {return(paste(i,"is a Miller-Rabin witness!"))}
A=FPM(i,q,n)
a=A
for(j in 0:(k-1))
{
if( a==(n-1) )
{
j=0
break
}
a=(a^2)%%n
}
if (j==(n-1) & A != 1) {return(paste(i,"is a Miller-Rabin witness!"))}
}
paste(n,"passes the Miller-Rabin test!")
}
MR.test(17)
MR.test(121)
MR.test(341) #Almost composite yields fermat witness 2, but 341=11*31 doesn't.
MR.test(561) #Carmicheal number 56 = 3*11*17
MR.test(1031) #1031 is a prime
MR.test(1105) #Carmicheal number 1105 = 5*13*17
MR.test(1729) #Carmicheal number 1729 = 7*13*19
MR.test(41041) #Carmicheal number 41041 = 7*11*13*41
Below is the result of running the code.
Unlike the Fermat Test, the Miller-Rabin test can also catch Carmichael numbers such as , , , .
Silverman. (2012). A Friendly Introduction to Number Theory (4th Edition): p137. ↩︎