题解 P5451 【[THUPC2018]密码学第三次小作业】

· · 题解

update:修了下括号

题中给出了m^{e1}与m^{e2}的值,我们可以轻易求出m^{e1-e2}的值,即

m^{e1-e2}=m^{e1}/m^{e2}

更进一步地,有

m^{e1\%e2}=m^{e1}/(m^{e2})^{\lfloor e1/e2 \rfloor}

从而,与求gcd结构类似地,我们可以通过辗转相除法求出m^1,即m。因为e1,e2互质,他们的gcd为1,故我们最终求出的m的指数为1

对于同余除法,求出其逆元再相乘即可。

此题范围达到了2^{64},需要使用龟速乘。还有几个细节我将在注释中说明。

#include<bits/stdc++.h>
#define int long long
#define U unsigned
using namespace std;
int a,b,x,y,c1,c2,e1,e2,mod,inv,t,o,c3,n=1;
void exgcd(int &x,int &y,int a,int b){
    if(!b){
        x=1,y=0;
    }
    else{
        int p,q;
        exgcd(q,p,b,a%b);
        x=p,y=q-a/b*p;
    }
}//使用exgcd求逆元存在负数,不可使用unsigned

U int smul(int x,int y){
    U int ans=0,a=(U int)x,b=(U int)y;
    while(b){
        if(b&1)ans=(ans+a)%mod;
        b>>=1,a=(a+a)%mod;
    }
    return ans;
}//龟速乘中加法也会超出longlong范围,使用unsigend

int qpow(int a,int b){
    int ans=1;
    while(b){
        if(b&1)ans=smul(ans,a);
        b>>=1,a=smul(a,a);
    }
    return ans;
}


signed main(){
    cin>>n;
    while(n--){
        cin>>c1>>c2>>e1>>e2>>mod;
        if(e1<e2)swap(e1,e2),swap(c1,c2);
        while(e2!=1){
            exgcd(x,y,c2,mod),t=e1/e2,o=e1%e2;
            x=(x%mod+mod)%mod;//x为e2逆元,所以除以e2等同于乘x
            c3=smul(c1,qpow(x,t))%mod;//快速幂防超时
            c1=c2,c2=c3,e1=e2,e2=o;
        }
        cout<<c2<<endl;
    }
    return 0;
}

该算法的复杂度上限为log^3n(即辗转相除,快速幂幂和龟速乘复杂度相乘)。跑不满,因为当辗转相除复杂度增加时,快速幂复杂度会下去;并且实际上辗转相除的复杂度是达不到log的。所以正常的复杂度是低于log^2n的,可以通过此题。