![](http://acm.fzu.edu.cn/image/problem.gif)
Accept: 596 Submit: 2010
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 4 2 10 1000
Sample Output
1 24
求解a^b%c,因为b的数值太大,只能使用公式转换 a^b%c = a^( b%phic+phic )%c;
只要求出phic后就可以将b转化为一个可以存下的整数,然后使用快速幂,就可以求解出结果。
不要有一个要注意,就是这个公式使用的条件,那就是 b > phic ,所以要先判断 b的大小
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
#define LL __int64
char s[1100000] ;
LL getphi(LL n)
{
LL ans = n , m = (LL)sqrt(n+0.5);
LL i , j ;
for(i = 2 ; i <= m ; i++)
{
if( n%i == 0 )
{
ans = ans / i * (i-1) ;
while( n%i==0 )
n /= i ;
}
}
if( n > 1 )
ans = ans / n * (n-1);
return ans ;
}
LL pow_mod(LL a,LL b,LL c)
{
if( b == 0 )
return 1 ;
LL ans = pow_mod(a,b/2,c);
ans = ans * ans %c ;
if( b%2 )
ans = ans*a%c;
return ans;
}
int main()
{
LL a , c , i , l , phic , b ;
while(scanf("%I64d %s %I64d", &a, s, &c)!=EOF)
{
l = strlen(s);
phic = getphi(c);
if( l < 10 )
{
b = 0 ;
for(i = 0 ; i < l ; i++)
b = b*10 + (s[i] -'0');
printf("%I64d\n", pow_mod(a,b,c));
continue ;
}
b = (s[0] - '0')%phic ;
for(i = 1 ; i < l ; i++)
{
b %= phic ;
b = ( b*10 + s[i]-'0' )%phic ;
}
b += phic ;
printf("%I64d\n", pow_mod(a,b,c) );
}
}