Miller_Rabin判断素数模版

#include<bits/stdc++.h>

using namespace std;

typedef long long ll;
const int maxn=1000100;
const int INF=1e9+10;

/// 18位素数:154590409516822759
/// 19位素数:2305843009213693951 (梅森素数)
/// 19位素数:4384957924686954497
ll prime[6] = {2, 3, 5, 233, 331};
ll qmul(ll x,ll y,ll mod)
{ // 乘法防止溢出, 如果p * p不爆LL的话可以直接乘; O(1)乘法或者转化成二进制加法
    return (x*y-(ll)(x/(long double)mod*y+(1e-3))*mod+mod)%mod;
}

ll qpow(ll n,ll k,ll mod)
{
    ll res=1;
    while(k){
        if(k&1) res=qmul(res,n,mod);
        n=qmul(n,n,mod);
        k>>=1;
    }
    return res;
}

bool Miller_Rabin(ll p) {
    if(p<2) return 0;
    if(p!=2&&p%2==0) return 0;
    ll s=p-1;
    while(!(s&1)) s>>=1;
    for(int i=0;i<5;i++) {
        if(p==prime[i]) return 1;
        ll t=s,m=qpow(prime[i],s,p);
        while(t!=p-1&&m!=1&m!=p-1) {
            m=qmul(m,m,p);
            t<<=1;
        }
        if(m!=p-1&&!(t&1)) return 0;
    }
    return 1;
}

int main()
{
    ll n;
    while(cin>>n){
        if(Miller_Rabin(n)) cout<<"YES"<<endl;
        else cout<<"NO"<<endl;
    }
    return 0;
}
View Code

 

posted @ 2016-02-02 02:38  __560  阅读(189)  评论(0编辑  收藏  举报