To think of a beautiful problem description is so hard for me that let’s just drop them off. 😃
Given four integers a,m,n,k,and S = gcd(am-1,an-1)%k,calculate the S.
InputThe first line contain a t,then t cases followed.
Each case contain four integers a,m,n,k(1<=a,m,n,k<=10000).OutputOne line with a integer S.
Sample Input
1
1 1 1 1
Sample Output
0
题意:有a,m,n,k,求有给出等式得到的s;
解题思想: S = gcd(a ^ m-1 , a ^ n-1)%k 这个等式的运用,可以看出是快速幂和gcd的使用,这得借助一个等式变化:gcd (a ^ m - b ^ m , a ^ n - b ^ n) = a ^ gcd(m,n)-b^gcd(m,n);有这个等式解决,可以看出b=1时就是此等式的标准形式,所有最终只需要求解 S = gcd ( a ^ m-1 , a ^n-1)%k=a ^gcd(m,n)-1,就可以了。
#include <iostream>
using namespace std;
typedef long long ll;
int mod;
int gcd(int a,int b)
{
return b?gcd(b,a%b):a;
}
long long pow(ll x,ll y)
{
ll cnt=1;
x=x%mod;
while(y)
{
if(y&1) cnt=(cnt*x)%mod;
y/=2;
x=(x*x)%mod;
}
return cnt;
}
int main()
{
int t;
cin>>t;
while(t--)
{
ll a,m,n,k,ans;
cin>>a>>m>>n>>k;
mod=k;
ll y=gcd(m,n);
ans=(mod+pow(a,y)-1)%mod;
cout<<ans<<endl;
}
return 0;
}