import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        long a;
        long b;
        long p;
        for(int i = 0;i<n;i++){
            a = in.nextInt();
            b = in.nextInt();
            p = in.nextInt();
            System.out.println(quickn(a,b,p));
        }
    }
    public static long quickn(long a,long b,long p){
        long res = 1;
        while(b > 0){
            if(b%2==1){
                res = res * a % p;
            }
            b /= 2;
            a = a * a % p;
        }
        return res;
    }
}