#include <stdio.h> int main() { int q; scanf("%d",&q); while(q--) { long long a,b,p; scanf("%lld%lld%lld",&a,&b,&p); int result=1; a%=p; while(b>0) { if(b%2==1) { result=(result*a)%p; } b/=2; if(b>0) { a=(a*a)%p; } } printf("%d\n",result); } return 0; }