#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; #define PN true //素数 #define NPN false //素数ではない #define MAXRR 5000010 //√MAXR以上の数を設定する //MAXRまでの整数は素数であると仮定する(ここから削る) vector PN_chk(MAXRR + 1, PN);//0indexでi番目が整数iに対応(0~MAXR) //素数を格納する配列を用意しておく vector PNs; void se() { //0と1は素数ではない PN_chk[0] = NPN; PN_chk[1] = NPN; FOR(i, 2, MAXRR) { //たどり着いた時に素数と仮定されているなら素数 if (PN_chk[i]) FOR(j, i, ll(MAXRR / i)) { PN_chk[j*i] = NPN; } } FOR(i, 2, MAXRR) { if (PN_chk[i]) PNs.push_back(i); } } 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 (!PN_chk[P])return -1; int N = P * (P + 1) / 2; return modpow(A, N, P); } signed main() { cin.tie(0); ios::sync_with_stdio(false); se(); int t; cin >> t; while (t--) { int A, P; cin >> A >> P; cout << solve(A, P) << '\n'; } return 0; }