pollard pho&miller rabin模板

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011056504/article/details/79096876

大数分解质因数和快速判断质数
结果在p里面

#define ll long long
#define fo(i,a,b) for(int i=a;i<=b;i++)
ll mul(ll a,ll b,ll mo)
{
    ll jy=0;
    for(;b;b/=2,a=(a+a)%mo) if(b%2==1) jy=(jy+a)%mo;
    return jy;
}
ll mi(ll a,ll b,ll mo)
{
    ll c=1;a%=mo;
    for(;b;b/=2,a=mul(a,a,mo)) if(b%2==1) c=mul(c,a,mo);
    return c;
}
bool miller_rabin(ll n)
{
    if(n==2) return 1;
    if(n%2==0) return 0;
    ll r=n-1;int j=0;
    for(;r%2==0;r/=2) j++;
    fo(i,1,8)
    {
        ll a=(ll)rand()*(ll)rand()%(n-2)+2;
        ll x=mi(a,r,n),las=x;
        fo(k,1,j)
        {
            x=mul(x,x,n);
            if(x==1&&las!=1&&las!=n-1) return 0;
            las=x;
        }
        if(x!=1) return 0;
    }
    return 1;
}
ll rd(ll x,ll n,ll c){return (mul(x,x,n)+c)%n;}
ll pollard_rho(ll n,ll c)
{
    ll x=rand()%(n-2)+2,y=x,d;
    if(n%x==0) return x;
    while(1)
    {
        x=rd(x,n,c);
        y=rd(rd(y,n,c),n,c);
        if(y==x) return n;
        d=gcd(abs(x-y),n);
        if(d>1&&d<n) return d;
    }
}
void find(ll n,ll c)
{
    if(n==1) return;
    if(miller_rabin(n))
    {
        if(bz[n]==0) p[++p[0]]=n,bz[n]=1;
        return;
    }
    ll p=n;
    while(p==n) p=pollard_rho(n,c--);
    find(p,c);find(n/p,c);
}
int main()
{
    find(n,(ll)rand()*(ll)rand());
}

猜你喜欢

转载自blog.csdn.net/u011056504/article/details/79096876
今日推荐