#include<cstdio>
typedef long long ll;

ll gcd(ll a,ll b)
{
	return !b?a:gcd(b,a%b);
}

int fpow(int a,ll b,int c)
{
	ll w=1,o=a;
	while(b) {
		if(b&1) w=w*o%c;
		o=o*o%c;
		b>>=1;
	}
	return w;
}

int Phi(int n)
{
	int r=n;
	for(int i=2; i*i<=n; i++)
		if(n%i==0)
		{
			r=r/i*(i-1);
			while(n%i==0)n/=i;
		}
	if(n>1)r=r/n*(n-1);
	return r;
}

ll exgcd(ll a,ll b,ll&x,ll&y)
{
	if(!b)
	{
		x=1;
		y=0;
		return a;
	}
	ll c=exgcd(b,a%b,x,y);
	ll t=x;
	x=y;
	y=t-a/b*y;
	return c;
}

ll Inv(ll a,ll b)
{
	ll x,y;
	exgcd(a,b,x,y);
	return(x+b)%b;
}

ll now,M;

void excrt(ll a,ll b)
{
	ll c=((a-now)%b+b)%b;
	ll x,y;
	ll d=exgcd(M,b,x,y);
	if(c%d!=0) throw -1;
	c/=d;
	b/=d;
	x=(x%b+b)%b;
	x=(__int128)x*c%b;
	now+=x*M;
	M*=b;
}

int T,n,m;
ll k;

ll solve(int d)
{
	if(d==1)
		return 1;
	int pd=Phi(d);
	ll y=solve(gcd(d,pd));
	now=y%pd;
	M=pd;
	excrt(fpow(n,y,d),d);
	while(now<=0) now+=(ll)d*pd;
	return now;
}

int main()
{
	scanf("%d",&T);
	while(T--)
	{
		scanf("%d%d",&n,&m);
		printf("%lld\n",solve(m));
	}
	return 0;
}