/*
模线性方程ax=b (mod n),令d=exgcd(a,n),该方程有解的充要条件为 d | b ,即 b% d==0
方程ax=b(mod n)的最小解 :x=(x*(b/d))%n
方程ax=b(mod n)的最小正数解: x=(x%(n/d)+n/d)%(n/d)
因为要求输出最小整数,所以如果答案为0的话,肯定是m=1的情况,此情况应输出1.
*/
# include<stdio.h>
# include<algorithm>
# include<string.h>
using namespace std;
int e_gcd(int a,int b,int &x,int &y)
{
if(b==0)
{
x=1;
y=0;
return a;
}
int ans=e_gcd(b,a%b,x,y);
int temp=x;
x=y;
y=temp-a/b*y;
return ans;
}
int main()
{
int t,a,m;
while(~scanf("%d",&t))
{
while(t--)
{
scanf("%d%d",&a,&m);
int b=1;
int x,y;
int d=e_gcd(a,m,x,y);
if(b%d!=0)
printf("Not Exist\n");
else
{
x=(x%(m/d)+m/d)%(m/d);
if(x==0)
x=1;
printf("%d\n",x);
}
}
}
return 0;
}