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

int T,a,b,p;

void solve(){
	
	int t_a=a,t_b=b,sum=1;
	
	while(true){
		if(t_b==0) break;
		if(t_b&1==1){
			sum=sum*t_a%p;
		}else{
			//不做操作 
		}
		t_a=t_a*t_a%p;
		t_b=t_b>>1;
	}
	
	cout<<sum%p<<endl;
}

signed main(){
	ios::sync_with_stdio(false);
	cin.tie(0);
	
	cin>>T;
	
	while(T--){
		
		cin>>a>>b>>p;
		
		solve();
		
		
	}
	
	
    return 0;
}