#include<bits/stdc++.h>
using namespace std;
#define fast ios::sync_with_stdio(NULL); cin.tie(0); cout.tie(0);
typedef long long ll;
const ll N = 100111, MOD = 1e9 + 7;
ll t, n, a;
int main()
{
fast
cin >> t;
while(t--)
{
cin >> n >> a;
for(ll b = n; b > max(n - 2000, 1ll); b--)
{
ll g = __gcd(a, b);
if(g == 1)
{
cout << b << endl;
break;
}
}
}
}