Discription
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.
Input
The first line contain a t,then t cases followed.
Each case contain four integers a,m,n,k(1<=a,m,n,k<=10000).
Output
One line with a integer S.
Sample Input
1
1 1 1 1
Sample Output
0
题意
给定四个数:a,m,n,k
求解:S = gcd(am-1,an-1)%k
思路
套用定理:
gcd(a^m−1,a^n−1)=a^gcd(m,n)−1
AC代码
#include<bits/stdc++.h>
using namespace std;
long long qmi(int m, int k, int p)
{
long long res = 1 % p, t = m;
while (k)
{
if (k&1) res = res * t % p;
t = t * t % p;
k >>= 1;
}
return res;
}
int t;
int a,m,n,k;
long long ans;
int main()
{
scanf("%d",&t);
while(t--)
{
scanf("%d%d%d%d",&a,&m,&n,&k);
int tmp=__gcd(m,n);
ans=(qmi(a,tmp,k)+k-1)%k;
printf("%lld\n",ans);
}
return 0;
}