题目链接:http://acm.fzu.edu.cn/problem.php?pid=1759
题目: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
思路:由于B的数据太大,因而我们需要借助欧拉定理来进行降幂,然后再用快速幂解决。
代码实现如下:
#include <cstdio>
#include <cstring> const int maxn = 1e6 + ;
long long a, b, c;
char s[maxn]; int euler(int x) {
int ans = x;
for(int i = ; i * i <= x; i++) {
if(x % i == ) {
ans = ans / i * (i - );
while(x % i == ) x /= i;
}
}
if(x > ) ans = ans / x * (x - );
return ans;
} long long ModPow(int n, int p, int mod) {
long long rec = ;
while(p) {
if(p & ) rec = rec * n % mod;
n = (long long) n * n % mod;
p >>= ;
}
return rec;
} int main() {
while(~scanf("%lld%s%lld", &a, s, &c)) {
b = ;
int rec = euler(c);
int len = strlen(s);
for(int i = ; i < len; i++) {
b = b % rec;
b = ((s[i] - '') + * b) % rec;
}
b += rec;
printf("%lld\n", ModPow(a, b, c));
}
return ;
}