#include<bits/stdc++.h> typedef unsigned long long ull; using namespace std; ull kmod(ull x,ull n,ull mod){ ull res = 1; if(x == 1 || n == 0) return 1; while(n > 0){ if(n & 1) res = (res * (x)%mod) % mod; x = ((x)%mod * (x)%mod) % mod; n >>= 1; } return res; } ull F[1000002]; int main(){ F[0] = 0,F[1] = 1; ull a,b,n,T; cin >> T; while(T--){ cin >> a >> b >> n; if(n == 1){ cout << 0 << endl; continue; //注意这里是continue。。 } int f1 = 0,f2 = 1,l = 0; for(int i = 2;i <= n*n;i++){ F[i] = (F[i-1] + F[i-2])%n; //cout << F[i] << endl; if(F[i] == f2 && F[i-1] == f1){ l = i - 1; break; } } //cout << "l:" << l << endl; ull ans = kmod(a%l,b,l); ///这里先模一下,否则ans会出错 //cout << "ans:" << ans << endl; cout << F[ans] << endl; } return 0; }