#include #include #include #include #include #include #include #include #include using namespace std; typedef long long ll; #define int long long #define double long double typedef vector VI; typedef pair pii; typedef vector VP; typedef vector VS; typedef priority_queue PQ; templatebool chmax(T &a, const T &b) { if (a < b) { a = b; return 1; } return 0; } templatebool chmin(T &a, const T &b) { if (b < a) { a = b; return 1; } return 0; } #define fore(i,a) for(auto &i:a) #define REP(i,n) for(int i=0;i, greater > q2; bool sosuu(int num) { if (num < 2)return false; else if (num == 2)return true; else if (num % 2 == 0)return false; for (int i = 3; i * i <= num; i++) { if (num % i == 0) return false; } return true; } int modpow(int a, int p,int mo) { if (p == 0) return 1; if (p % 2 == 0) { int halfP = p / 2; int half = modpow(a, halfP,mo); return half * half % mo; } else { return a * modpow(a, p - 1,mo) % mo; } } int solve(int A, int P) { if (!sosuu(P))return -1; int N = P * (P + 1) / 2; return modpow(A, N, P); } signed main() { cin.tie(0); ios::sync_with_stdio(false); int t; cin >> t; while (t--) { int A, P; cin >> A >> P; cout << solve(A, P) << '\n'; } return 0; }