快速判断素数:Miller算法
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <vector>
#include <ctime>
using namespace std;
typedef long long ll;
typedef pair<int,int> P;
const int maxn=1e6+10;
const ll inf=1e12;
ll mult_mod(ll a,ll b,ll c)
{
a%=c;
b%=c;
ll ret=0,tmp=a;
while(b)
{
if(b&1){
ret+=tmp;
if(ret>c)ret-=c;
}
tmp<<=1;
if(tmp>c)tmp-=c;
b>>=1;
}
return ret;
}
ll qpow(ll x,ll n,ll mod){
if(n==1)return x%mod;
ll tmp=x%mod;
ll ret=1;
while(n){
if(n&1)ret=mult_mod(ret,tmp,mod);
tmp=mult_mod(tmp,tmp,mod);
n>>=1;
}
return ret;
}
bool check(ll a,ll n,ll x,ll t){
ll ret=qpow(a,x,n);
ll last=ret;
for(int i=1;i<=t;i++){
ret=mult_mod(ret,ret,n);
if(ret==1&&last!=1&&last!=n-1)return true;
last=ret;
}
if(ret!=1)return true;
return false;
}
bool Miller(ll n){
if(n<2)return false;
if(n==2||n==3||n==5||n==7)return true;
if((n%2==0)||(n%3==0)||(n%5==0)||(n%7==0))return false;
ll x=n-1;
ll t=0;
while((x&1)==0){x>>=1;t++;}
srand((unsigned)time(NULL));
for(int i=0;i<10;i++){
ll a=rand()%(n-1)+1;
if(check(a,n,x,t))return false;
}
return true;
}
int main(){
ll x;
while(cin>>x){
if(Miller(x)) printf("YES\n");
else printf("NO\n");
}
return 0;
}