#include<bits/stdc++.h>
#define ull unsigned long long
#define ll long long
#define all(x) x.begin(), x.end()
using namespace std;
const int maxn = 1e6 + 5;
int SOLVE(int a, int b) {
if (a == b) return 0;
int res = INT_MAX;
for (int i = 2; i <= sqrt(a); ++i) {
if (a % i == 0) {
if(b%i==0) res = min(res, ((b / i) * i) - b);
res = min(res, ((b / i + 1) * i) - b);
if (a / i != i) {
if(b%(a/i)==0) res = min(res, ((b / (a / i)) * (a / i)) - b);
res = min(res, ((b / (a / i) + 1) * (a / i)) - b);
}
}
}
if (res == INT_MAX) {
return abs(a - b);
}
return res;
}
int main() {
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
int n, a, b;
cin >> n;
while (n--) {
cin >> a >> b;
cout << SOLVE(a, b) << endl;
}
}
I2luY2x1ZGU8Yml0cy9zdGRjKysuaD4KI2RlZmluZSB1bGwgdW5zaWduZWQgbG9uZyBsb25nCiNkZWZpbmUgbGwgbG9uZyBsb25nCiNkZWZpbmUgYWxsKHgpIHguYmVnaW4oKSwgeC5lbmQoKQp1c2luZyBuYW1lc3BhY2Ugc3RkOwpjb25zdCBpbnQgbWF4biA9IDFlNiArIDU7CmludCBTT0xWRShpbnQgYSwgaW50IGIpIHsKICAgIGlmIChhID09IGIpIHJldHVybiAwOwogICAgaW50IHJlcyA9IElOVF9NQVg7CiAgICBmb3IgKGludCBpID0gMjsgaSA8PSBzcXJ0KGEpOyArK2kpIHsKICAgICAgICBpZiAoYSAlIGkgPT0gMCkgewogICAgICAgICAgICBpZihiJWk9PTApIHJlcyA9IG1pbihyZXMsICgoYiAvIGkpICogaSkgLSBiKTsKICAgICAgICAgICAgcmVzID0gbWluKHJlcywgKChiIC8gaSArIDEpICogaSkgLSBiKTsKICAgICAgICAgICAgaWYgKGEgLyBpICE9IGkpIHsKICAgICAgICAgICAgICAgIGlmKGIlKGEvaSk9PTApIHJlcyA9IG1pbihyZXMsICgoYiAvIChhIC8gaSkpICogKGEgLyBpKSkgLSBiKTsKICAgICAgICAgICAgICAgIHJlcyA9IG1pbihyZXMsICgoYiAvIChhIC8gaSkgKyAxKSAqIChhIC8gaSkpIC0gYik7CiAgICAgICAgICAgIH0KICAgICAgICB9CiAgICB9CiAgICBpZiAocmVzID09IElOVF9NQVgpIHsKICAgICAgICByZXR1cm4gYWJzKGEgLSBiKTsKICAgIH0KICAgIHJldHVybiByZXM7Cn0KaW50IG1haW4oKSB7CiAgICBpb3NfYmFzZTo6c3luY193aXRoX3N0ZGlvKDApOyBjaW4udGllKDApOyBjb3V0LnRpZSgwKTsKICAgIGludCBuLCBhLCBiOwogICAgY2luID4+IG47CiAgICB3aGlsZSAobi0tKSB7CiAgICAgICAgY2luID4+IGEgPj4gYjsKICAgICAgICBjb3V0IDw8IFNPTFZFKGEsIGIpIDw8IGVuZGw7CiAgICB9Cn0KCg==