Given A,B,C, You should quickly calculate the result of ABmodC A B m o d C . (1<=A,C<=1000000000,1<=B<=101000000). ( 1 <= A , C <= 1000000000 , 1 <= B <= 10 1000000 ) .
Input
There are multiply testcases. Each testcase, there is one line contains three integers A, B and C, separated by a single space.
Output
For each testcase, output an integer, denotes the result of A^B mod C.
Sample Input
3 2 4
2 10 1000
Sample Output
1
24
思路:因为幂的数量级很大,肯定不能直接算。用欧拉定理降幂就行,前几天遇到过个类似的题,这个算是一般化了。
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
using namespace std;
long long phi(long long x)
{
long long ans=x;
for(long long i=2;i*i<=x;i++)
{
if(x%i==0)
{
ans=ans/i*(i-1);
while(x%i==0)
x/=i;
}
}
if(x>1)
ans=ans/x*(x-1);
return ans;
}
long long get(long long a,long long b,long long mod)
{
long long ans=1;
while(b)
{
if(b&1)
ans=ans*a%mod;
a=a*a%mod;
b>>=1;
}
return ans;
}
long long a,c;
char b[1000005];
int main()
{
while(scanf("%lld%s%lld",&a,b,&c)==3)
{
long long P=phi(c);
long long left=0;
int len=strlen(b);
for(int i=0;i<len;i++)
{
left=left*10+b[i]-'0';
if(left>P)
left%=P;
}
cout<<get(a,left,c)<<endl;
}
return 0;
}