#include <bits/stdc++.h>
#define rep(i,l,r) for (int i=l,i##end=r;i<=i##end;++i)
#define per(i,r,l) for (int i=r,i##end=l;i>=i##end;--i)
#define rep0(i,r) for (int i=0,i##end=r;i<i##end;++i)
#define ll long long
using namespace std;
ll M;
ll mul(ll x,ll y,ll m){
    ll s=0; for (;y;y>>=1,x=(x+x)%m) if (y&1) s=(s+x)%m;
    return s;
}
ll fpw(ll x,ll y,ll m){
    ll s=1; x%=m;
    for (;y;y>>=1,x=x*x%m) if (y&1) s=s*x%m;
    return s;
}
ll gcd(ll x,ll y){ return y==0?x:gcd(y,x%y); }
void exgcd(ll a,ll b,ll &x,ll &y){
    if (b==0){ x=1,y=0; return; }
    exgcd(b,a%b,y,x); y-=a/b*x;
}
ll phi(ll n){
    ll s=1;
    rep(i,2,sqrt(n))
        if (n%i==0){
            s*=i-1,n/=i; while (n%i==0) s*=i,n/=i;
            if (n==1) break;
        }
    return s*(n==1?1:n-1);
}
ll solve(ll a,ll m){
    if (m==1) return M;
    ll p=phi(m),g=gcd(m,p),_y=solve(a,g);
    ll pw=fpw(a,_y,m),c=_y%p-pw;
    //ans=m*x+pw=p*y+_y m*x-p*y=pw-_y
    //m*x-p*y=c
    ll x1,y1; exgcd(m,p,x1,y1);
    x1=(x1%(p/g)+(p/g))%(p/g)*(c/g);
    ll d=m*p/g; x1=(x1%d+d)%d;
    ll ans=(mul(x1,m,d)+pw)%d;
    while (ans<M) ans+=d;
    return ans;
}
int main(){
    int q; cin>>q;
    while (q--){
        ll a,m; cin>>a>>m; M=100;
        ll s=solve(a,m); cout<<s<<endl;
    }
    return 0;
}