#include <bits/stdc++.h>
using namespace std;

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    int t;
    cin>>t;
    while(t--){
        long long a,b,p,res=1;
        cin>>a>>b>>p;
        if(p==1){
            cout<<"0\n";
            continue;
        }
        a%=p;
        while(b){
            if(b&1)
            res=(res*a)%p;
            a=(a*a)%p;
            b>>=1;
        }
        cout<<res<<'\n';
    }
}
// 64 位输出请用 printf("%lld")