//https://codeforc.es/gym/104279
#include <bits/stdc++.h>
#define ll long long
#define all(a) (a).begin(), (a).end()
using namespace std;
const int inf = 0x3f3f3f3f;
const ll INF = 0x3f3f3f3f3f3f3f3f;
const int N = 5e5 + 10;
/*
init() 解决本质不同的长度为 n 的 01 环的个数问题
计算 : f(n) 表示最小循环节为 n 的 01 串(直线上)的方案数
f(n) = 2^n - f(n 的所有因子)
则长度为 n 的环的方案数为: sum : f(fac) / i, fac 为 n 的因子
*/
ll mod = 998244353;
ll ans[N];
ll f[N];
ll qpow(ll base, ll pow)
{
ll ans = 1;
while (pow)
{
if (pow & 1) ans = ans * base % mod;
pow >>= 1;
base = base * base % mod;
}
return ans;
}
inline ll inv(ll x){
return qpow(x, mod - 2);
}
void init()
{
f[1] = 2;
for (int i = 2; i < N; i++) f[i] = f[i - 1] * 2 % mod;
for (int i = 1; i < N; i++)
for (int j = i + i; j < N; j += i)
f[j] = (f[j] - f[i] + mod) % mod;
for (int i = 1; i < N; i++)
for (int j = i, res = f[i] * inv(i) % mod; j < N; j += i)
ans[j] = (ans[j] + res) % mod;
}
void solve()
{
ll n, k;
cin >> n >> k;
int m = gcd(k, n);
cout << ans[m] << '\n';
}
signed main()
{
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
init();
int t = 1;
cin >> t;
while (t--) solve();
return 0;
}