#include using namespace std; #define For(i, a, b) for(int i = (a); i < (b); i++) #define rep(i, n) For(i, 0, n) #define rFor(i, a, b) for(int i = (a); i >= (b); i--) #define ALL(v) (v).begin(), (v).end() #define rALL(v) (v).rbegin(), (v).rend() using lint = long long; using ld = long double; int INF = 2000000000; lint LINF = 1000000000000000000; struct SetupIo { SetupIo() { ios::sync_with_stdio(false); cin.tie(nullptr); cout << fixed << setprecision(15); } } setupio; namespace math { template T div_floor(T a, T b) { assert(b != 0); if (b < 0) { a = -a; b = -b; } return (a >= 0 ? a / b : (a + 1) / b - 1); } template T div_ceil(T a, T b) { assert(b != 0); if (b < 0) { a = -a; b = -b; } return (a > 0 ? (a - 1) / b + 1 : a / b); } template T bin_gcd(T a_, T b_) { unsigned long long a = abs(a_), b = abs(b_); if (a == 0 || b == 0) { return (a == 0 ? b : a); } int x = __builtin_ctzll(a), y = __builtin_ctzll(b); a >>= x; b >>= y; while (a != b) { if (a < b) { swap(a, b); } a -= b; a >>= __builtin_ctzll(a); } return (a << min(x, y)); } template T ext_gcd(T a, T b, T &x, T &y) { if (b == 0) { x = (a >= 0 ? 1 : -1); y = 0; return abs(a); } T g = ext_gcd(b, a % b, y, x); y -= a / b * x; return g; } template T bezout_coef(T a, T b, T c, T &x, T &y) { T g = ext_gcd(a, b, x, y); if (abs(c) % g) { return -1; } a /= g, b /= g, c /= g; if (b == 0) { x *= c; return g; } using bint = __int128_t; bint nx = bint(x) * bint(c); bint ny = bint(y) * bint(c); bint q = (b < 0 ? div_floor(-nx, b) : div_ceil(-nx, b)); nx += b * q; ny -= a * q; x = nx; y = ny; return g; } } // namespace math using namespace math; const lint mod = 1000000000; int main() { int t; cin >> t; while (t--) { lint n, m; cin >> n >> m; lint x, y; lint g = bezout_coef(n, -mod, -m, x, y); if (g == -1) { cout << -1 << "\n"; } else { if (x == 0) { x += mod / g; } cout << x << "\n"; } } }