题解 P5451 【[THUPC2018]密码学第三次小作业】
update:修了下括号
题中给出了
更进一步地,有
从而,与求gcd结构类似地,我们可以通过辗转相除法求出
对于同余除法,求出其逆元再相乘即可。
此题范围达到了
#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;
}
该算法的复杂度上限为