Because of the existence of pseudo prime number, Fermat prime test has a great flaw, so there is the Miller-Rabin primality test.
Template:
#include <iostream>#include<cmath>using namespacestd;Long LongQpow (intAintBintR//Fast Power{ Long Longans=1, buff=A; while(b) {if(b&1) ans= (ans*buff)%R; Buff= (buff*buff)%R; b>>=1; } returnans;}BOOLMiller_rabbin (intNintA//Millerabine Prime number test{ intR=0, s=n-1, J; if(! (n%a))return false; while(! (s&1) ) {s>>=1; R++; } Long Longk=Qpow (a,s,n); if(k==1) return true; for(j=0; j<r;j++,k=k*k%N)if(k==n-1) return true; return false;}BOOLIsPrime (intN//determine if it is a prime number{ inttab[]={2,3,5,7}; for(intI=0;i<4; i++) { if(n==Tab[i])return true; if(!Miller_rabbin (N,tab[i]))return false; } return true;}intMain () {Long LongN; while(1) {cin>>N; cout<< isprime (n) <<Endl; } return 0;}
Algorithm notes--Miller-robin Prime test