#include<bits/stdc++.h>
#define rep(i,a,b) for(ll i=(a);i<=(b);i++)
#define per(i,a,b) for(ll i=(a);i>=(b);i--)
#define ll long long
using namespace std;
const ll N=2e6;
ll flag,mod,a,m,b;
ll read(){
ll num=0;char ch=getchar();
while(!isdigit(ch))ch=getchar();
while(isdigit(ch)){
num=1LL*num*10+ch-'0',ch=getchar();
if(num>=mod){
flag=1;
num%=mod;
}
}
return num;
}
ll mul(ll a,ll b,ll mod){
ll ans=0;for(;b;b>>=1,a=(a+a)%mod)if(b&1)ans=(ans+a)%mod;return ans;
}
ll power(ll a,ll b,ll mod){
ll ans=1;for(;b;b>>=1,a=1LL*a*a%mod)if(b&1)ans=1LL*ans*a%mod;return ans;
}
ll phi(ll n){
int ans=n;
rep(i,2,sqrt(n)){
if(n%i)continue;
ans=ans/i*(i-1);
while(n%i==0)n/=i;
}if(n>1)ans=ans/n*(n-1);
return ans;
}
int main()
{
scanf("%d%d",&a,&m);
mod=phi(m); b=read();
if(flag)cout<<1LL*power(a,b,m)*power(a,mod,m)%m;
else cout<<power(a,b,m);
return 0;
}
#include<bits/stdc++.h>
#define rep(i,a,b) for(int i=(a);i<=(b);i++)
#define per(i,a,b) for(int i=(a);i>=(b);i--)
using namespace std;
map<int,int> f;
int T,n;
inline void Print(int x){if(x>9)Print(x/10);putchar(x%10+'0');}
int power(int a,int b,int mod)
{int ans=1;for(;b;b>>=1,a=1LL*a*a%mod)if(b&1)ans=1LL*ans*a%mod;return ans;}
int phi(int n){
int ans=n;
rep(i,2,sqrt(n)){
if(n%i)continue;
ans=ans/i*(i-1);
while(n%i==0)n/=i;
}if(n>1)ans=ans/n*(n-1);
return ans;
}
int F(int n){
if(f.count(n))return f[n];
int p=phi(n);
return f[n]=power(2,F(p)+p,n);
}
int main()
{
scanf("%d",&T);
f[1]=0;
while(T--){
scanf("%d",&n);
Print(F(n));puts("");
}return 0;
}