[SinGuLaRiTy] Miller Robin prime number determination method, singularity Miller
[SinGuLaRiTy-1003] Copyright (c) SinGuLaRiTy 2017. All Rights Reserved.
Background
A number of prime number testing methods have been developed by using the Fermat's theorem. The Miller-Rabbin prime number testing algorithm is a fast one.
Procedure
(1) calculate an odd number of M, so that N = 2 ^ r * M + 1;
(2) select random number A <N;
(3) For any I <r, if A ^ (2 ^ I * M) mod N = N-1, N passes the test of random number;
(4) or, if A ^ M mod N = 1, N passes the test of random number;
(5) Let A get different values and perform multiple tests on N (generally, 5 ~ 10 times, 20 ~ 30 times), if all pass, the N is determined as the prime number;
Probability
If N passes a test, the probability that N is not a prime number is 25%;
If N passes t tests, the probability that N is not a prime number is 1/(4 ^ t );
In fact, when t = 5, the probability that N is not a prime number is already 1/128, and it is already greater than 99.99%.
In practical use, you can use 300 ~ N is tested with 500 small prime numbers to increase the probability of passing the test and the speed of the algorithm. In the randomly generated prime number, it is best to set the random number to r = 0, which can save the operation in step (3) and further reduce the determination time.
Code
#include<cstdlib>#include<ctime>#include<cstdio>using namespace std;const int count=10;int modular_exp(int a,int m,int n){ if(m==0) return 1; if(m==1) return (a%n); long long w=modular_exp(a,m/2,n); w=w*w%n; if(m&1) w=w*a%n; return w;} bool Miller_Rabin(int n){ if(n==2) return true; for(int i=0;i<count;i++) { int a=rand()%(n-2)+2; if(modular_exp(a,n,n)!=a) return false; } return true;}int main(){ srand(time(NULL)); int n; scanf("%d",&n); if(Miller_Rabin(n)) printf("Probably a prime."); else printf("A composite."); printf("\n"); return 0;}
Time: