#include <iostream>
using namespace std;

int kpow(long long a, int b, int p){    //注意a要取long long
    if(p==1) return 0;
    int res=1;
    a%=p;
    while(b){
        if(b%2) res=(res*a)%p;
        a=(a*a)%p;
        b>>=1;
    }
    return res;
}

int main() {
    int a, b, p, t;
    cin>>t;
    while (t--) { 
        cin>>a>>b>>p;
        cout<<kpow(a, b, p)<<endl;
    }
    return 0;
}