#include<cstdio>
typedef long long LL;
int qmi(int a,int k,int p)
{
int res=1;
while(k)
{
if(k&1)
{
res=(LL)res*a%p;
}
a=(LL)a*a%p;
k>>=1;
}
return res;
}
int main()
{
int n;
scanf("%d",&n);
while(n--)
{
int a,k,p;
scanf("%d%d%d",&a,&k,&p);
printf("%d\n",qmi(a,k,p));
}
return 0;
}