快速分解质因数,Miller_Rabin+Pollard_rho

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/samjia2000/article/details/54618716
int getrand(){
    int s=rand()%10;
    fo(i,1,5)s=s*10+rand()%10;
    return s+2;
}

LL quickmi(LL x,LL tim,LL mo){
    LL ans=1;
    while(tim){
        if (tim%2)ans=ans*x%mo;
        x=x*x%mo;
        tim/=2;
    }
    return ans;
}

bool check(int x,int p,int q,int mo){
    LL now=quickmi(x,p,mo);
    if (now==1||now==mo-1)return 1;
    fo(i,1,q){
        if (now==1)return 0;
        now=now*now%mo;
        if (now==1||now==mo-1)return 1;
    }
    if (now!=1)return 0;
    return 1;
}

bool miller_rabin(int x){
    if (x<2)return 0;
    if (x==2)return 1;
    if (x%2==0)return 0;
    int v=x-1,s=0;
    while(v%2==0)v/=2,s++;
    fo(i,1,10){
        int w=getrand()%x;
        while(w==0)w=getrand()%x;
        if (!check(w,v,s,x))return 0;
    }
    return 1;
}

int gcd(int x,int y){
    if (!y)return x;
    return gcd(y,x%y);
}

int ran_f(LL x,int c,int mo){return (x*x+c)%mo;}

int pollard_rho(int x,int c){
    LL i=1,k=2;
    int x0=getrand()%x,y=x0;
    for(;;){
        i++;
        x0=(LL(x0)*x0+c)%x;
        int d=gcd(abs(y-x0),x);
        if (d!=1&&d!=x)return d;
        if (y==x0)return x;
        if (i==k){y=x0;k+=k;}
    }
}

void getfac(int x){
    if (x==1)return;
    if (miller_rabin(x)){
        a[++k]=x;
        return;
    }
    int p=pollard_rho(x,getrand()%(x-1)+1);
    getfac(p);
    getfac(x/p);
}
阅读更多
换一批

没有更多推荐了,返回首页