// (⁠◕⁠ᴗ⁠◕⁠✿⁠) #include #pragma GCC target("avx2") #pragma GCC optimize("O3") #pragma GCC optimize("unroll-loops") #define rep(i, n) for (ll i = 0; i < (n); i++) #define srep(i, s, n) for (ll i = s; i < (n); i++) #define len(x) ((int)(x).size()) #define all(x) (x).begin(), (x).end() using namespace std; template using vc = vector; template using vv = vc>; template using vvv = vv>; using vi = vc;using vvi = vv; using vvvi = vv; using ll = long long;using vl = vc;using vvl = vv; using vvvl = vv; using ld = long double; using vld = vc; using vvld = vc; using vvvld = vc; using uint = unsigned int; using ull = unsigned long long; const ld pi = acos(-1.0); const int inf = 0x3f3f3f3f; const ll INF = 0x3f3f3f3f3f3f3f3f; // const ll mod = 1000000007; const ll mod = 998244353; inline bool inside(ll y, ll x, ll H, ll W) {return 0 <= (y) and (y) < (H) and 0 <= (x) and (x) < (W); } #define debug(var) do{std::cout << #var << " : \n";view(var);}while(0) template void view(T e){cout << e << endl;} template void view(const vc& v){for(const auto& e : v){ cout << e << " "; } cout << endl;} template void view(const vv& vv){ for(const auto& v : vv){ view(v); } } vc> factorization(ll &N){ vc> factors; ll tmp = N; for (ll i = 2; i * i <= N + 1; i++){ if (tmp % i == 0){ int cnt = 0; while (tmp % i == 0){ tmp /= i; cnt += 1; } factors.push_back({i, cnt}); } } if (tmp != 1){ factors.push_back({tmp, 1}); } if (len(factors) == 0){ factors.push_back({N, 1}); } return factors; } void solve(){ ll A, B;cin >> A >> B; ll C = B - A; if (C == 0){ cout << 0 << endl; return; } auto factor = factorization(C); ll ans = INF; function dfs = [&](int p, ll nw){ if (len(factor) == p) return; auto [prime, num] = factor[p]; dfs(p + 1, nw); if (nw >= A) ans = min(ans, nw - A); rep(i, num){ nw *= prime; if (nw >= A){ ans = min(ans, nw - A); break; } dfs(p + 1, nw); } }; dfs(0, 1); if (ans == INF) cout << -1 << endl; else cout << ans << endl; } int main(){ int T; cin >> T; while (T--) solve(); }