/*
solution:
同余模运算
首先要观察到其周期性,设F[i] = f[i]%n; F[i]呈现周期性的规律。
找到这个规律的周期t,就可以轻松求出F[a^b]。
note:
注意对a^b%n的正确姿势是pow_mod(a%t[n], b, t[n])。
而不是pow_mod(a, b, t[n])。这个很容易写错!
date:
2016.8.19
*/
#include <iostream>
#include <cstdio>
using namespace std;
const int maxn = 1001;
typedef unsigned long long ull;
int F[maxn][maxn*6]; //F[i][j]表示n=i时 f(j)%n
int t[maxn]; //t[i]表示在n=i情况下的周期长度
int n;
ull a, b;
int pow_mod(ull a, ull n, int m) {
if(n == 0) return 1;
int x = pow_mod(a, n/2, m);
long long ans = (long long)x * x % m;
if(n % 2 == 1) ans = ans * a % m;
return (int)ans;
}
int main() {
//freopen("input.txt", "r", stdin);
for(int n = 2; n <= 1000; n++) {
F[n][0] = 0; F[n][1] = 1;
for(int i = 2; ; i++) {
F[n][i] = (F[n][i-1] + F[n][i-2]) % n;
if(F[n][i-1] == 0 && F[n][i] == 1) {
t[n] = i - 1;
break;
}
}
} //预处理打表
int kase;
cin >> kase;
while(kase--) {
cin >> a >> b >> n;
if(n == 0 || n == 1) cout << "0" << endl;
else {
int tmp = pow_mod(a%t[n], b, t[n]);
cout << F[n][tmp] << endl;
}
}
return 0;
}
uva11582(同余模基础)
最新推荐文章于 2021-10-20 01:34:15 发布