#include #define rep(i, n) for (int i = 0; i < (n); i++) #define rrep(i, n) for (int i = (n - 1); i >= 0; i--) #define ALL(v) v.begin(), v.end() using namespace std; using P = pair; typedef long long ll; const ll MAX_N = 5000000; ll prime[MAX_N]; bool is_prime[MAX_N + 1]; //エラトステネスの篩 void sieve(ll n){ ll p = 0; n = MAX_N; for (int i = 0; i <= n; i++) is_prime[i] = true; is_prime[0] = is_prime[1] = false; for (int i = 2; i <= n; i++){ if(is_prime[i]){ prime[p++] = i; for (int j = 2 * i; j <= n; j += i)is_prime[j] = false; } } } long long modpow(long long a, long long n, long long mod) { long long res = 1; while (n > 0) { if (n & 1) res = res * a % mod; a = a * a % mod; n >>= 1; } return res; } void solve() { ll a; int b; cin >> a >> b; if(!is_prime[b]){ cout << -1 << endl; return; } if(a % b == 0){ cout << 0 << endl; return; } ll sum = (ll)(1 + b) * b / 2; ll num = (ll)sum % (b - 1); cout << modpow(a, num, b) << endl; } int main(){ sieve(MAX_N); int t; cin >> t; rep(i, t) solve(); }