This prime-number algorithm is based on an extension of the Fermat theorem.
Fermat theorem : for prime number p and any integer A, there is a^p≡a (mod p) (congruence). Conversely, if A^p≡a (mod p) is satisfied, p also has a large probability of being prime. A a^ (p-1) ≡1 (mod p) will be asked to go to both sides at the same time.
That is to say, suppose we want to test whether n is a prime number. We can randomly pick a number a, and then calculate a^ (n-1) mod n, if the result is not 1, we can 100% to conclude that N is not prime.
Otherwise we will randomly select a new number A to test. So repeatedly, if each result is 1, we assume that N is prime.
This test is known as the Fermat test . It is important to note that the Fermat test is not necessarily accurate, and it is possible to have a case where composite is misjudged as a prime number.
Miller and Rabin in the Fermat test, the Miller-rabin prime number test algorithm is established.
A two-time detection theorem was added compared to the Fermat test:
If P is an odd prime, then the solution for X^2≡1 (MoD) p is x≡1 or x≡p-1 (mod p)
Pseudo code:
miller-Rabin (N): If (n<=2) then If (n==2) then return True End If return False End If if (n mod2==0) Then//N is an even number that is not 2 and returns directly to compositeReturn False End If//we first find the smallest a^u, and then gradually expand to a^ (n-1)u= N-1;//U represents exponential while(U%2==0) U= u/2End while//Extraction factor 2For i=1.. S//S is the number of tests setA = Rand_number (2N1)//Random acquisition of a 2~n-1 number ax = a^u%n while (U<N)//check each adjacent a^u, a^2u, a^4u, ... a^ (2^k*u) to meet the two-time detection theoremy = x^2%n If (y==1and x! =1and x! = N-1)//Two-time detection theorem//If y = x^2≡1 (mod n)//but X! = 1 and x! = n-1Return False End If x=y u= U *2End while If (x!=1) Then//Fermat Testreturn False end If end for Return True
Written in C + + code:
//quickly determine if it is prime#include <iostream>#include<time.h>#include<algorithm>#defineSS 100#definell Long Longusing namespacestd; ll Mod_mul (ll A, ll B, ll N) {ll res=0; while(b) {if(B &1) Res = (res + a)%N; A= (A + a)%N; b>>=1; } returnRes;}//Fast Power (a^b)%nll Mod_exp (ll A, ll B, ll N) {ll res=1; while(b) {if(B &1) res =Mod_mul (Res, a, n); A=Mod_mul (A, A, n); b>>=1; } returnRes;}BOOLMillerrabin (ll x) {if(x = =2)return true; if(x%2==0|| X <2)return false; ll u= X1; while(u%2==0) U = u/2; for(inti =1; I <= SS; i++) {srand (unsigned) time (NULL)); ll a= (rand ()% (X-2)) +2; ll xx=Mod_exp (A, u, x); while(u<x) {ll yy= Mod_exp (xx,2, x); if(yy = =1&& XX! =1&& XX! = X1)return false; XX= Yy,u = u*2; } if(xx!=1)return false; } return true;}intMain () {intN; CIN>>N; while(n--) {ll number; CIN>>Number ; cout<< (millerrabin)?"Yes":"No") <<Endl; } return 0;}
View Code
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Miller-rabin Prime number Test