package competitive;
import java.util.*;
public class MathDay {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t-- > 0) {
long a = sc.nextLong();
long n = sc.nextLong();
long p = sc.nextLong();
long ans = a%p;
for (int i = 2; i <= n; i++) {
ans = power(ans, i, p) ;
ans%=p;
}
System.out.println(ans);
}
}
public static long power(long ans, long b, long p) {
if (b == 0) {
return 1;
}
if ((b & 1) != 0) {
return (ans * (power(ans, b / 2, p)))%p ;
} else {
long s = power(ans, b / 2, p)%p ;
return (s*s)%p;
}
}
}