#include using namespace std; #define ll long long #define ld long double #define REP(i,m,n) for(int i=(int)(m); i<(int)(n); i++) #define rep(i,n) REP(i,0,n) #define RREP(i,m,n) for(int i=(int)(m); i>=(int)(n); i--) #define rrep(i,n) RREP(i,n-1,0) #define all(v) v.begin(), v.end() const int inf = 1e9+7; const ll longinf = 1LL<<60; const ll mod = 1e9+7; const ld eps = 1e-10; bool is_prime(const ll n) { switch(n) { case 0: // fall-through case 1: return false; case 2: // fall-through case 3: return true; } if(n % 2 == 0) return false; if(n % 3 == 0) return false; if(n % 6 != 1 && n % 6 != 5) return false; for(ll i=5; i*i<=n; i+=6) { if(n % i == 0) return false; // 6n-1 if(n % (i+2) == 0) return false; // 6n+1 } return true; } ll modpow(ll a, ll N, ll mod=mod) { ll ans = 1; ll tmp = a; while(N > 0) { if(N % 2 == 1) (ans *= tmp) %= mod; (tmp *= tmp) %= mod; N /= 2; } return ans; } void solve() { ll a, p; cin >> a >> p; if(!is_prime(p)) cout << -1 << endl; else { ll ans = 1; rep(i, p) (ans *= modpow(a, i+1, p)) %= p; cout << ans << endl; } } int main() { cin.tie(0); ios::sync_with_stdio(false); int t; cin >> t; while(t--) { solve(); } return 0; }