bzoj4522 [Cqoi2016]密钥破解(pollard-rho大数分解+逆元)

其实就是把大数n分解了,再exgcd求个逆元。

#include 
using namespace std;
#define ll long long
#define inf 0x3f3f3f3f
#define ld long double
#define eps 1e-8
inline char gc(){
    static char buf[1<<16],*S,*T;
    if(S==T){T=(S=buf)+fread(buf,1,1<<16,stdin);if(T==S) return EOF;}
    return *S++;
}
inline ll read(){
    ll x=0,f=1;char ch=gc();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=gc();}
    while(ch>='0'&&ch<='9') x=x*10+ch-'0',ch=gc();
    return x*f;
}
ll e,n,c,step;
inline ll mul(ll x,ll y,ll mod){
    ll res=x*y-(ll)((ld)x/mod*y+eps)*mod;res%=mod;return res<0?res+mod:res;
}
inline ll gcd(ll x,ll y){return y?gcd(y,x%y):x;}
inline void exgcd(ll a,ll b,ll &x,ll &y){
    if(!b){x=1;y=0;return;}
    exgcd(b,a%b,x,y);ll t=x;x=y;y=t-a/b*y;
}
inline ll ksm(ll x,ll k,ll mod){
    ll res=1;for(;k;k>>=1,x=mul(x,x,mod)) if(k&1) res=mul(res,x,mod);return res;
}
inline ll f(ll x){return (mul(x,x,n)+step)%n;}
inline ll pollard_rho(ll n){
    while(1){
        step=rand();ll a=rand(),b=a;
        while(1){
            a=f(a),b=f(f(b));
            if(a==b) break;
            ll g=gcd(abs(a-b),n);
            if(g!=1) return g;
        }
    }
}
int main(){
//  freopen("crack10.in","r",stdin);
    e=read();n=read();c=read();srand(20000711);
    ll p=pollard_rho(n),q=n/p;
    ll r=(p-1)*(q-1);ll d,y;
    exgcd(e,r,d,y);d%=r;if(d<0) d+=r;
    printf("%lld %lld\n",d,ksm(c,d,n));
    return 0;
}

你可能感兴趣的:(bzoj,素数,扩展欧几里得算法)