P4358 [CQOI2016]密钥破解(Pollrad_Rho)

· · 个人记录

题意

没什么好说的,照着题目要求的求即可,主要复习下Pollrad_Rho。

code:

#include<bits/stdc++.h>
using namespace std;
#define int long long
int e,c,N,p,q,r,d,n,x;
inline int read()
{
    char c=getchar();int res=0,f=1;
    while(c<'0'||c>'9'){if(c=='-')f=-1;c=getchar();}
    while(c>='0'&&c<='9')res=res*10+c-'0',c=getchar();
    return res*f;
}
inline int mul(int x,int y,int mod){return (x*y-(long long)((long double)x*y/mod)*mod+mod)%mod;}
inline int power(int x,int k,int mod)
{
    int res=1;
    while(k)
    {
        if(k&1)res=mul(res,x,mod);
        x=mul(x,x,mod);k>>=1;
    }
    return res;
}
int gcd(int a,int b){return !b?a:gcd(b,a%b);}
inline bool Miller_Rabin(int a,int p)
{
    if(power(a,p-1,p)!=1)return 0;
    int k=p-1;
    while(!(k&1))
    {
        k>>=1;
        int t=power(a,k,p);
        if(t!=1&&t!=p-1)return 0;
        if(t==p-1)return 1;
    }
    return 1;
}
inline bool check(int x)
{
    if(x==1)return 0;
    if(x==2||x==3||x==5||x==7||x==11||x==13)return 1;
    return Miller_Rabin(2,x)&&Miller_Rabin(3,x)&&Miller_Rabin(5,x)&&Miller_Rabin(7,x)&&Miller_Rabin(11,x)&&Miller_Rabin(13,x);
}
void Pollard_Rho(int n)
{
    if(check(n)){p=n;return;}
    int t1=rand()%(n-1)+1,t2=t1,delta=rand()%(n-1)+1;
    t2=(mul(t2,t2,n)+delta)%n;
    int now=1,cnt=0;
    while(t1!=t2)
    {
        cnt++;
        now=mul(now,abs(t1-t2),n);
        if(!now)
        {
            int t=gcd(abs(t1-t2),n);
            if(t!=1&&t!=n)Pollard_Rho(t),Pollard_Rho(n/t);
            return;
        }
        if(cnt%127==0)
        {
            int t=gcd(now,n);
            if(t!=1&&t!=n){Pollard_Rho(t);Pollard_Rho(n/t);return;}
            now=1,cnt=0;
        }
        t1=(mul(t1,t1,n)+delta)%n;
        t2=(mul(t2,t2,n)+delta)%n;
        t2=(mul(t2,t2,n)+delta)%n;
    }
    int t=gcd(now,n);
    if(t!=1&&t!=n)Pollard_Rho(t),Pollard_Rho(n/t);
}
void exgcd(int a,int b,int& x,int& y)
{
    if(!b){x=1;y=0;return;}
    exgcd(b,a%b,x,y);
    int z=x;x=y,y=z-(a/b)*y;
}
signed main()
{
    srand(time(0));
    e=read(),N=read(),c=read();
    Pollard_Rho(N);q=N/p;
    r=(p-1)*(q-1);
    exgcd(e,r,d,x);
    d=(d%r+r)%r;
    n=power(c,d,N);
    printf("%lld %lld",d,n);
    return 0;
}