#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; void find_divisor(ll N, vector& divisor) { for(int i=1; i<=sqrt(N); i++) { if(N % i == 0) divisor.push_back(i); } int n = divisor.size(); for(int i=n-1; i>=0; i--) { if(N != (ll)pow(divisor[i], 2)) divisor.push_back(N / divisor[i]); } } 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; vector div; find_divisor(p, div); if(div.size() != 2) cout << -1 << endl; else { ll ans = a; rep(i, p) ans = modpow(ans, i+1)%p; cout << ans << endl; } } int main() { cin.tie(0); ios::sync_with_stdio(false); int t; cin >> t; while(t--) { solve(); } return 0; }