fzu Problem 1649 Prime number or not
思路:miller_rabin 大素数测试
#include <cstdio> #include <iostream> #include <cstring> #include <algorithm> #include <cmath> #include <cstdlib> using namespace std; #define Times 10 long long random(long long n) { return ((double)rand()/RAND_MAX*n+0.5); } long long multi(long long a,long long b,long long m) { long long ans=0; while(b) { if(b&1) { b--; ans=(ans+a)%m; } else { b/=2; a=(2*a)%m; } } return ans; } long long Pow(long long a,long long b,long long m) { long long ans=1; while(b) { if(b&1) { b--; ans=multi(ans,a,m); } else { b/=2; a=multi(a,a,m); } } return ans; } bool witness(long long a,long long n) { long long d=n-1; while(!(d&1)) d>>=1; long long t=Pow(a,d,n); while(d!=n-1 && t!=1 && t!=n-1) { t=multi(t,t,n); d<<=1; } return t==n-1 || d&1 ; } bool miller_rabin(long long n) { if(n==2) return true; if(n<2||!(n&1)) return false; for(int i=1;i<=Times;i++) { long long a=random(n-2)+1; if(!witness(a,n)) return false; } return true; } int main() { long long n; while(cin>>n) { if(miller_rabin(n)) cout<<"It is a prime number."<<endl; else cout<<"It is not a prime number."<<endl; } return 0; }