# https://atcoder.jp/contests/abc186/tasks/abc186_e from math import gcd T = int(input()) for _ in range(T): N, M = map(int, input().split()) MOD = 10 ** 9 N, S, K = MOD, M, N if K % MOD == 0: print(1 if S % MOD == 0 else -1) continue g = gcd(K, N) if S % g: print(-1) else: N //= g S //= g K //= g # print(N, S, K) # ans = -S * K^-1 (mod N) ans = (N - S * pow(K, -1, N)) % N if ans == 0: ans += N print(ans)