#include long long gcd (long long a, long long b) { if (b <= 0LL) { return a; } return gcd(b, a%b); } long long power_mod (long long a, long long b, long long mod_num) { long long ans = 1LL; if (b > 0LL) { ans = power_mod(a, b/2LL, mod_num); ans = (ans * ans) % mod_num; if (b%2LL == 1LL) { ans = (ans * a) % mod_num; } } return ans; } int main () { int t = 0; long long h = 0LL; long long w = 0LL; int res = 0; long long mod_num = 998244353LL; long long div[1000] = {}; res = scanf("%d", &t); while (t > 0) { long long ans = 0LL; long long d = 0LL; int div_cnt = 0; res = scanf("%lld", &h); res = scanf("%lld", &w); d = gcd(h, w); for (int i = 1; i*i <= ((int)d); i++) { if (((int)d)%i == 0) { div[div_cnt] = (long long)i; div_cnt++; if (((int)d)/i != i) { div[div_cnt] = d/((long long)i); div_cnt++; } } } for (int i = 0; i < div_cnt; i++) { if (div[i] == 4LL) { ans += 16LL; ans %= mod_num; } else if (div[i] >= 10LL && (div[i]-10LL)%6LL == 0LL) { long long tmp = power_mod((div[i]-4LL)/3LL, d/div[i]-1LL, mod_num); tmp *= (div[i]*div[i])%mod_num; tmp %= mod_num; ans += tmp; ans %= mod_num; } } ans += h*w; ans %= mod_num; if (d > 3LL) { ans += 2LL*d; ans %= mod_num; } if (d > 3LL && d%3LL == 0LL) { ans += 6LL*d; ans %= mod_num; } printf("%lld\n", ans); t--; } return 0; }