f(a^b)对n求余后会有周期出现,只需找出它等同于周期中的哪一项即可。最好提前打表。
#include<cstdio>
#include<cstring>
#include<cctype>
#include<cstdlib>
#include<cmath>
#include<iostream>
#include<sstream>
#include<iterator>
#include<algorithm>
#include<string>
#include<vector>
#include<set>
#include<map>
#include<deque>
#include<queue>
#include<stack>
#include<list>
typedef long long ll;
typedef unsigned long long llu;
const int MAXN = 1000 + 10;
const int MAXT = 10000 + 10;
const int INF = 0x7f7f7f7f;
const double pi = acos(-1.0);
const double EPS = 1e-6;
using namespace std;
int mp[MAXN][6 * MAXN], num[MAXN];
void init(){
for(int i = 2; i < MAXN; ++i){
mp[i][0] = 0;
mp[i][1] = 1;
for(int j = 2; ; ++j){
mp[i][j] = (mp[i][j - 1] + mp[i][j - 2]) % i;
if(mp[i][j] == 1 && mp[i][j - 1] == 0){
num[i] = j - 1;
break;
}
}
}
}
llu pow_mod(llu a, llu i, llu n){
if(i == 0) return 1 % n;
llu tmp = pow_mod(a, i >> 1, n);
tmp = tmp * tmp % n;
if(i & 1) tmp = (ll)tmp * a % n;
return tmp;
}
int main(){
init();
int T;
llu a, b, n;
scanf("%d", &T);
while(T--){
scanf("%llu%llu%llu", &a, &b, &n);
if(n == 1 || a == 0){
printf("0\n");
continue;
}
int tmp = pow_mod(a % num[n], b, num[n]);
printf("%d\n", mp[n][tmp]);
}
return 0;
}