#include using namespace std; typedef long long int ll; typedef pair P; typedef vector VI; typedef vector VVI; const ll MOD = 1000000007; const ll INF = 1e18; #define REP(i, n) for(int i = 0; i < n; i++) #define ALL(v) v.begin(), v.end() ll power(ll x, ll y, ll p) { if (y==0) return 1; else if (y==1) return x%p; else if (y%2==0) { ll pow=power(x,y/2,p); return (pow*pow)%p; } else { ll pow=power(x,y/2,p); return ((pow*pow)%p)*x%p; } } int main() { int t; cin >> t; while(t--){ ll a, p; cin >> a >> p; bool no=0; for(int i=2;i<=sqrt(p);i++){ if(p%i==0){ printf("-1\n"); no=1; } } if(no) continue; ll f=0; for(int i=1;i<=p;i++){ f*=i; f%=(p-1); } printf("%ld\n",power(a,f,p)); } return 0; }