#include /*#include #include */#pragma GCC target("avx") #pragma GCC optimize("O3") #pragma GCC optimize("unroll-loops") using namespace std; /*namespace mp = boost::multiprecision; using Bint = mp::cpp_int; using Real = mp::number>; */#define lli long long int #define uli unsigned long long int #define INF 999999999999 #define rep(i,m,n) for(lli i = m;i < n;i++) #define rrep(i,m,n) for(lli i=m-1;i>=n;i--) #define pb(n) push_back(n) #define UE(N) N.erase(unique(N.begin(),N.end()),N.end()); #define Sort(n) sort(n.begin(), n.end()) #define Rev(n) reverse(n.begin(),n.end()) #define Out(S) cout << S << endl #define NeOut(S) cout << S #define HpOut(S) cout << setprecision(50) << S << endl #define Vec(K,L,N,S) vector K(N,S) #define DV(K,L,N,M,S) vector> K(N,vector(M,S)) #define TV(K,L,N,M,R,S) vector>> K(N,vector>(M,vector(R,S))) #define pint pair #define paf(L,R) pair #define mod 1000000007 #define MAX 10000000 #define ALL(a) a.begin(),a.end() #define chmax(a, b) a = (((a)<(b)) ? (b) : (a)) #define chmin(a, b) a = (((a)>(b)) ? (b) : (a)) vectorprime_table(int n){ vectorprime(n+1,1); if(n>=0)prime[0]=0; if(n>=1)prime[1]=0; for(int i=2;i*i<=n;i++){ if(!prime[i])continue; for(int j=i+i;j<=n;j+=i){ prime[j]=0; } } return prime; } lli modpow(lli n,lli k,lli m){ if(k==0)return 1; else if(k%2==1)return modpow(n,k-1,m)*n%m; else{ lli temp=modpow(n,k/2,m); return temp*temp%m; } } int main(){ ios::sync_with_stdio(false); cin.tie(0); long long A, P, N, D, M, K, T; long long sum = 0; cin >> T; auto Pt = prime_table(10000000); while(T--){ cin >> A >> P; if(Pt[P])cout << modpow(A,P-2,P) << endl; else cout << -1 << endl; } }