#include <stdio.h>
int GCD(int a,int b)
{
return b?GCD(b,a%b):a;
}
int main(void)
{
int n;
scanf("%d",&n);
while(n--)
{
int a,b,c=0;
scanf("%d%d",&a,&b);
while(++c)
{
if(c==b)continue;
if(GCD(a,c)==b)break;
}
printf("%d\n",c);
}
return 0;
}