Problem 1759 Super A^B mod C
Accept: 572 Submit: 1919
Time Limit: 1000 mSec Memory Limit : 32768 KB
Problem Description
Given A,B,C, You should quickly calculate the result of A^B mod C. (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 42 10 1000
Sample Output
124
欧拉函数的应用
A^x = A^(x mod Phi(C) + Phi(C)) (mod C)
#include<set>
#include<queue>
#include<cmath>
#include<cstdio>
#include<vector>
#include<string>
#include<utility>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<functional>
#define Inf (1<<30)
#define LL long long
#define MOD 1000000009
#pragma comment(linker, "/STACK:102400000,102400000")
using namespace std;
LL a,c;
char b[1000100];
LL phi(LL x)
{
LL res=x;
for(LL i=2;i*i<=x;i++)
{
if(x%i==0)
{
res=res/i*(i-1);
while(x%i==0)x/=i;
}
}
if(x>1)res=res/x*(x-1);
return res;
}
LL qpow(LL x,LL y)
{
LL res=1;
while(y>0)
{
if(y&1)res=(res*x)%c;
y>>=1;
x=(x*x)%c;
}
return (res+c)%c;
}
int main()
{
int T;
while(~scanf("%lld%s%lld",&a,b,&c))
{
LL mod=phi(c),L=strlen(b),res=0;
for(LL i=0;i<L;i++)
res=(res*10+b[i]-'0')%mod;
res+=mod;
printf("%lld\n",qpow(a,res));
}
return 0;
}