#include #define rep(i,n) for(int i=(0);i<(n);i++) using namespace std; typedef long long ll; template bool chmax(T &a, const T &b) { if (a bool chmin(T &a, const T &b) { if (a>b) { a=b; return 1; } return 0; } ll powmod(ll a, ll b, ll p){ if(b == 0) return 1; if(b & 1) { return a * powmod(a, b - 1, p) % p; } else { ll d = powmod(a, b / 2, p) % p; return d * d % p; } } ll solve(ll a, ll p){ for(int i = 2; i * i <= p; i++){ if(p % i == 0) return -1; } ll ret = powmod(a, p, p); return ret * (p - 1) % p; } int main(){ cin.tie(0); ios::sync_with_stdio(false); ll t; cin >> t; vector a(t), p(t); rep(i, t) cin >> a[i] >> p[i]; rep(i, t) cout << solve(a[i], p[i]) << "\n"; }