素数的判定,poj3641
#include<iostream> using namespace std; long long pow_mod(long long a,long long b,long long m) { long long t=a%m,res=1; while(b) { if(b&1) res=(res*t)%m; t=(t*t)%m; b/=2; } return res; } bool miller(long long k,long long d,long long n,long long a) { if(n==2||n==a) return true; if(!(n&1)) return false; long long i,t=pow_mod(a,d,n); if(t==1) return true; for(i=0;i<k;i++) { if(t==n-1) return true; t=(t*t)%n; } return false; } bool judge(long long n) { if(n<2) return false; long long k=0,d=n-1; while(!(d&1)) { k++; d>>=1; } if(n<1373653) { if(miller(k,d,n,2)&&miller(k,d,n,3)) return true; return false; } if(n<9080191) { if(miller(k,d,n,31)&&miller(k,d,n,73)) return true; return false; } if(n<4759123141) { if(miller(k,d,n,2)&&miller(k,d,n,3)&&miller(k,d,n,5)&&miller(k,d,n,11)) return true; return false; } if(n<2152302898747) { if(miller(k,d,n,2)&&miller(k,d,n,3)&&miller(k,d,n,5)&&miller(k,d,n,7)&&miller(k,d,n,11)) return true; return false; } else { if(miller(k,d,n,2)&&miller(k,d,n,3)&&miller(k,d,n,5)&&miller(k,d,n,7)&&miller(k,d,n,11)&&miller(k,d,n,31)&&miller(k,d,n,61)&&miller(k,d,n,73)) return true; return false; } } int main() { long long a,p; while(cin>>p>>a&&a) { if(judge(p)) cout<<"no"<<endl; else { if(pow_mod(a,p,p)==a) cout<<"yes"<<endl; else cout<<"no"<<endl; } } }
#include<iostream> using namespace std; typedef long long ll; ll txt[]={2,3,5,7,11,31,61}; long long pow_mod(long long a,long long b,long long m) { long long t=a%m,res=1; while(b) { if(b&1) res=(res*t)%m; t=(t*t)%m; b/=2; } return res; } bool miller(ll a,ll d,ll k,ll n) { if(n==2||n==a) return true; if(!(n&1)) return false; ll i,t=pow_mod(a,d,n); if(t==1) return true; for(i=0;i<k;i++) { if(t==n-1) return true; t=(t*t)%n; } return false; } bool judge(long long n) { if(n<2) return false; bool f; ll i,d=n-1,k=0; while(!(d&1)) { k++; d>>=1; } for(i=0;i<7;i++) if(!miller(txt[i],d,k,n)) return false; return true; } int main() { long long p,a; while(cin>>p>>a&&a) { if(judge(p)) cout<<"no"<<endl; else { if(pow_mod(a,p,p)==a) cout<<"yes"<<endl; else cout<<"no"<<endl; } } }