#include using namespace std; typedef long long ll; #define rep(i, srt, end) for (long long i = (srt); i < (long long)(end); i++) #define NMAX 5000100 bool primes[NMAX]; int main(){ rep(i, 2, NMAX) primes[i] = true; rep(i, 2, NMAX) { for(ll j = i * 2; j <= NMAX; j += i) primes[j] = false; } ll T = 0; cin >> T; rep(test, 0, T){ ll a, p; cin >> a >> p; if(!primes[p]) { cout << -1 << endl; continue; } ll rem = a % p; ll cur = rem, pw = rem, cnt = 0; while(cur != 0 && cnt < p * (p+1) / 2) { cnt++; cur *= pw; cur %= p; pw *= rem; pw %= p; } cout << cur << endl; } return 0; }