https://vjudge.net/problem/UVA-11582
题意:
输入两个非负整数a、b和正整数n,你的任务是计算f(a^b)除以n的余数。f[0]=0,f[1]=1,f[i+2]=f[i+1]+f[i]。
思路:
因为余数最多n种,所以最多n^2项就会出现重复。计算出周期,之后幂取模算出周期内的第几个数。
1 #include <iostream> 2 #include <cstring> 3 #include <algorithm> 4 #include <vector> 5 #include <queue> 6 #include <cmath> 7 using namespace std; 8 9 10 const int maxn = 1000 + 5; 11 typedef unsigned long long LL; 12 13 LL a, b; 14 int n; 15 int M; 16 17 int pow_mod(LL a, LL b, int m) 18 { 19 if (b == 0) return 1; 20 int x = pow_mod(a, b / 2, m); 21 LL ans = (LL)x*x%m; 22 if (b % 2) ans = ans*a%m; 23 return (int)ans; 24 } 25 26 int f[maxn*maxn], period[maxn]; 27 28 int solve(LL a, LL b, int n) { 29 if (a == 0 || n == 1) return 0; 30 int ans = pow_mod(a%M, b, M); 31 return f[ans]; 32 } 33 34 int main() 35 { 36 //freopen("D:\input.txt", "r", stdin); 37 int t; 38 scanf("%d", &t); 39 while (t--) 40 { 41 cin >> a >> b >> n; 42 f[0] = 0; 43 f[1] = 1; 44 for (int i = 2; i <= n*n; i++) 45 { 46 f[i] = (f[i - 1] + f[i - 2]) % n; 47 if (f[i - 1] == 0 && f[i] == 1) 48 { 49 M = i - 1; 50 break; 51 } 52 } 53 cout << solve(a, b, n) << endl; 54 } 55 }