#include <iostream>
using namespace std;
using ll=long long;
ll f(ll a,ll b,ll p){
    ll ans=1;
    a%=p;
    while(b){
        if(b&1){
            ans=(ans*a)%p;
            b-=1;
        }
        a=(a*a)%p;
        b/=2;
    }
    return ans;
}
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    ll a,b,q;
  int t;
  cin>>t;
  while(t--){
    cin>>a>>b>>q;
    cout<<f(a,b,q)<<endl;
  }
}
// 64 位输出请用 printf("%lld")