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();
        while (in.hasNextInt()) { 
            int a = in.nextInt();
            int b = in.nextInt();
            int p = in.nextInt();

            int tmp = (int)myPow(a,b,p);

           
            System.out.println(tmp);
        }
    }
 
    //递归求幂和求模:3的8 等于3的4乘3的4以此类推
    public static double myPow(int a,int b,int p){
        //截至函数
        if(b==0){
            return 1.0;
        }
        double tmp  = myPow(a,b/2,p);
        double ret = (tmp * tmp)%p;
        //当 b为奇数时需要再乘一个a;
        if(b%2==1){
            ret = (ret*a)%p;
        }
        return ret;

    }
}