#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<stack>
#include<vector>
#include<map>
#include<set>
#include<queue>
#include<algorithm>
using namespace std;
typedef unsigned long long ULL;
const int maxn = 1005;
int f[maxn][6*maxn],p[maxn];
int pow_mod(ULL a,ULL b,int n){
if(b==0) return 1;
int k=pow_mod(a,b/2,n);
k=k*k%n;
if(b%2==1) k=k*a%n;
return k;
}
int solve(ULL a,ULL b,int n){
if(a==0||n==1) return 0;
int idx=pow_mod(a%p[n],b,p[n]);
return f[n][idx];
}
int main()
{
int ncase;
int n;
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⑵]+f[n][i⑴])%n;
if(f[n][i⑴]==0&&f[n][i]==1){
p[n]=i⑴;
break;
}
}
}
scanf("%d",&ncase);
while(ncase--){
ULL a,b;
cin>>a>>b>>n;
cout<<solve(a,b,n)<<"
";
}
return 0;
}