题目链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1633
求一连串的幂,如果暴力算的话会溢出,题中会有一个求模,给出一个欧拉定理的应用:
x^y % m = x^(y % phi[m] + phi[m]) % m
递归求解即可。
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <cmath> 5 using namespace std; 6 7 const int maxn = 1111111; 8 int mod, n, x; 9 int a[maxn]; 10 char str[maxn]; 11 int phi[maxn]; 12 13 int quickmul(int x, int n, int mod) { 14 int ans = 1; 15 int t = x; 16 while(n) { 17 if(n & 1) { 18 ans = (ans * t) % mod; 19 } 20 t = t * t % mod; 21 n >>= 1; 22 } 23 return ans; 24 } 25 26 void geteular() { 27 memset(phi, 0, sizeof(phi)); 28 phi[1] = 1; 29 for(int i = 2; i < maxn; i++) { 30 if(!phi[i]) { 31 for(int j = i; j < maxn; j+=i) { 32 if(!phi[j]) { 33 phi[j] = j; 34 } 35 phi[j] = phi[j] / i * (i - 1); 36 } 37 } 38 } 39 } 40 41 int solve(int x, int m) { 42 if(x == n - 1) { 43 return a[x] % m; 44 } 45 return quickmul(a[x], solve(x+1, phi[m]) + phi[m], m); 46 } 47 48 int main() { 49 geteular(); 50 int kase = 1; 51 while(~scanf("%s", str) && strcmp(str, "#")) { 52 sscanf(str, "%d", &mod); 53 scanf("%d", &n); 54 for(int i = 0; i < n; i++) { 55 scanf("%d", &a[i]); 56 } 57 int ans = solve(0, mod); 58 printf("Case #%d: %d ", kase++, ans); 59 } 60 }