Millar Robin模板

(Millar Robin)模板

hdu2138

(Code)

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <ctime>
using namespace std;
typedef long long ll;

template<typename T>
inline void read(T &x)
{
    int f=1;char c;
    while((c=getchar())<'0'||c>'9') if(c=='-') f=-1;
    x=c^48;
    while((c=getchar())>='0'&&c<='9') x=(x<<1)+(x<<3)+(c^48);
    x*=f;
}

inline ll fpow(ll x,ll y,ll mod)
{
    ll ans=1;
    while(y)
    {
        if(y&1) ans=(ans*x)%mod;
        x=(x*x)%mod;y>>=1;
    }
    return ans;
}

inline int miller_rabin(int x)
{
    if(x==2) return 1;
    if(x==46856248255981l||x==1||(x%2)==0) return 0;
    ll u=x-1,ct=0;
    while((u%2)==0) u/=2,ct++;
    //printf("%d %d %d
",x,u,ct);
    for(int i=0;i<10;i++)
    {
        ll a=rand()%(x-1)+1;
        //cout<<a<<endl;
        ll xt=fpow(a,u,x);
        if(xt==1) continue;
        for(int j=1;j<=ct;j++)
        {
            ll y=xt*xt%x;
            if(y==1&&xt!=x-1&&xt!=1) return 0;
            xt=y;
        }
        if(xt!=1) return 0;
    }
    return 1;
}

int main()
{
    srand(time(0));
    int n,ans;
    ll x;
    while(scanf("%d",&n)!=EOF)
    {
        ans=0;
        while(n--)
        {
            read(x);
            ans+=miller_rabin(x);
        }
        printf("%d
",ans);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/gxm123/p/12810844.html