#include #define rep(i,n) for (int i=0; i < (n); i++) using namespace std; using ll = long long; ll mod; ll pow_kai(ll a, ll n){//aのn乗を計算します。 ll x = 1; while(n > 0){//全てのbitが捨てられるまで。 if(n&1){//1番右のbitが1のとき。 x = x*a; x %= mod; } a = a*a; a %= mod; n >>= 1;//bit全体を右に1つシフトして一番右を捨てる。 } return x; } int main(){ int testcase; cin>> testcase; vector vp(5000000+1,0); set prime; for(int i=2; i*i<=5000000; i++){ ll x=i+i; if(vp[x]==1) continue; while(x<=5000000){ vp[x]=1; x += i; } } while(testcase--){ ll A,P; cin>>A>>P; mod = P; // Aが素数かどうか。 bool pflg = false; if(vp[P]==0){ pflg=true; }else{ cout << -1 << endl; continue; } // Pが素数の時 ll rA=A%P; ll ans = pow_kai(rA,(P-1)/2 + 1)%mod; cout << ans << endl; } }