Miller_Rabin和Pollard Rho算法

废话不说贴代码
Pollard Rho
Miller_Rabin
Miller_Rabin

bool miller_rabin(LL aa,LL p)
{
    int cnt=0;
    LL res=p-1,u;
    while(res%2==0)
    {
        res/=2;
        cnt++;
    }
    u=ksm(aa,res,p);
    if(u==1)return 1;
    for(int i=0;i<cnt;i++)
    {
        if(u==p-1)return 1;
        u=mul(u,u,p);
    }
    return 0;
}   
bool isprime(LL p)
{
    if(p==2)return 1;
    if(p%2==0)return 0;
    for(int i=0;i<10;i++)
    {
        if(p==a[i])return 1;
        if(!(miller_rabin(a[i],p)))return 0;
    }
    return 1;
}
LL find_fac(LL p)
{
    if(p==4)return 2;
    while(1)            
    {
        LL c=rand()%p;
        LL v=0,u=0,d=0;
        while(1)
        {
            v=(mul(v,v,p)+c)%p;
            u=(mul(u,u,p)+c)%p;
            u=(mul(u,u,p)+c)%p;
            d=gcd(abs(u-v),p);
            if(d==p)break;
            if(d>1)return d;
        }
    }
}
void rho(LL p)
{
    if(p==1)return;
    if(isprime(p))
    {
        pr.insert(p);
    }
    else
    {
        LL d=find_fac(p);
        rho(d);
        rho(p/d);
    }
}

你可能感兴趣的:(算法)