HDU - 2685 寒假训练 gcd的性质 快速幂
原创
©著作权归作者所有:来自51CTO博客作者luer9的原创作品,请联系作者获取转载授权,否则将追究法律责任
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(a^m-1,a^n-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
Sample Input
1
1 1 1 1
Sample Output
0
代码如下
#include<iostream>
#include<math.h>
using namespace std;
typedef long long ll;
int gcd(int a,int b)
{
while(b!=0){
int c;
c=a%b;
a=b;
b=c;
}return a;
}
//gcd(a^m-b^m, a^n-b^n) = a^gcd(m,n)-b^gcd(m,n);这里b=1;
//gcd(a^m-1,a^n-1)=a^gcd(m,n)-1^gcd(m,n);
ll power (ll a,ll b,ll c)
{
int ans=1;
a=a%c;
while(b>0)
{
if(b%2==1)
{
ans=(ans*a)%c;
}
b=b/2;
a=(a*a)%c;
}return ans;
}
int main()
{
int t;
ll a,m,n,k;
cin>>t;
while(t--)
{
cin>>a>>m>>n>>k;
cout<<(power(a,gcd(m,n),k)+k-1)%k<<endl;//加k 防止出现-1
}return 0;
}