#include #define rep(i,n) for (int i = 0; i < (int)(n); i ++) #define irep(i,n) for (int i = (int)(n) - 1;i >= 0;--i) using namespace std; using ll = long long; using PL = pair; using P = pair; constexpr int INF = 1000000000; constexpr long long HINF = 1000000000000000; constexpr long long MOD = 1000000007;// = 998244353; constexpr double EPS = 1e-4; constexpr double PI = 3.14159265358979; vector sieve(int n) { vector prime(n + 1,true); prime[0] = false; prime[1] = false; rep(i,n + 1) { if (i%2 == 0) prime[i] = false; } prime[2] = true; for (int i = 3; i * i <= n; i += 2) { if (prime[i]) { int j = 2; while (i * j <= n) { prime[i * j] = false; j ++; } } } return prime; } template struct ModInt { long long x; ModInt(long long x = 0) :x((x%Modulus + Modulus)%Modulus) {} constexpr ModInt &operator+=(const ModInt a) {if ((x += a.x) >= Modulus) x -= Modulus; return *this;} constexpr ModInt &operator-=(const ModInt a) {if ((x += Modulus - a.x) >= Modulus) x -= Modulus; return *this;} constexpr ModInt &operator*=(const ModInt a) {(x *= a.x) %= Modulus; return *this;} constexpr ModInt &operator/=(const ModInt a) {return *this *= a.inverse();} constexpr ModInt operator+(const ModInt a) const {return ModInt(*this) += a.x;} constexpr ModInt operator-(const ModInt a) const {return ModInt(*this) -= a.x;} constexpr ModInt operator*(const ModInt a) const {return ModInt(*this) *= a.x;} constexpr ModInt operator/(const ModInt a) const {return ModInt(*this) /= a.x;} friend constexpr ostream& operator<<(ostream& os,const ModInt& a) {return os << a.x;} friend constexpr istream& operator>>(istream& is,ModInt& a) {return is >> a.x;} ModInt inverse() const {// x ^ (-1) long long a = x,b = Modulus,p = 1,q = 0; while (b) {long long d = a/b; a -= d*b; swap(a,b); p -= d*q; swap(p,q);} return ModInt(p); } ModInt pow(long long N) {// x ^ N ModInt a = 1; while (N) { if (N&1) a *= *this; *this *= *this; N >>= 1; } return a; } }; long long modpow(long long N,long long K,long long mod = MOD) { long long ret = 1; while (K > 0) { if (K&1) { ret *= N; ret %= mod; } K >>= 1; N *= N; N %= mod; } return ret; } const int MAXN = 500010; int main() { int T; cin >> T; vector primes = sieve(MAXN); rep(i,T) { ll A,P; cin >> A >> P; if (primes[P]) { if (A%P == 0) cout << 0 << '\n'; else { ll x = P*(P + 1)/2; x %= (P - 1); ll ans = modpow(A,x,P); cout << ans << '\n'; } } else { cout << -1 << '\n'; } } return 0; }