Miller Robin大素数判定


Miller Robin算法
当要判断的数过大,以至于根n的算法不可行时,可以采用这种方法来判定素数。
用于判断大于2的奇数(2和偶数需要手动判断),是概率意义上的判定,因此需要做多次来减少出错概率。

Template:

typedef long long ll;
ll kmul(ll a,ll b,ll mod)
{
    ll res=0;
    while (b)
    {
        if (b&1)
            res=(res+a)%mod;
        a=(a+a)%mod;
        b>>=1;
    }
    return res;
}
ll kpow(ll a,ll b,ll mod)
{
    ll res=1;
    while (b)
    {
        if (b&1)
            res=kmul(res,a,mod)%mod;
        a=kmul(a,a,mod)%mod;
        b>>=1;
    }
    return res;
}
bool Mil_Rb(ll n,ll a)
{
    ll d=n-1,s=0,i;
    while (!(d&1))
    {
        d>>=1;
        s++;
    }
    ll t=kpow(a,d,n);
    if (t==1||t==-1)
        return 1;
    for (i=0;i<s;++i)
    {
        if (t==n-1)
            return 1;
        t=kmul(t,t,n);
    }
    return 0;
}
bool is_prime(ll n)
{
    ll i,a[4]={3,5,7,11};
    for (i=0;i<4;++i)
    {
        if (n==a[i])
            return 1;
        if (!n%a[i])
            return 0;
        if (n>a[i]&&!Mil_Rb(n,a[i]))
            return 0;
    }
    return 1;
}

猜你喜欢

转载自www.cnblogs.com/orangee/p/9363584.html