#include <bits/stdc++.h>
using namespace std;
int m;
string N, M;
void print(string str) { for (int i = 0; i < str.size(); ++i) cout << (char)(str[i] + '0'); cout << endl; }
string add(string N, int x) {
reverse(N.begin(), N.end());
vector<int> res;
for (int i = 0; i < N.size(); ++i) res.push_back(N[i]);
res[0] += x;
for (int i = 0; i < res.size(); ++i) {
if (res[i] >= 10) {
if (i + 1 == res.size()) res.push_back(res[i] / 10);
else res[i + 1] += res[i] / 10;
res[i] %= 10;
}
}
reverse(res.begin(), res.end());
N = "";
for (int i = 0; i < res.size(); ++i) N.push_back(res[i]);
return N;
}
string solve1(){
ll r = 0;
for (int i = 0; i < N.size(); ++i) {
r = (r * 10 + N[i]) % m;
}
return add(N, m - r);
}
bool check1(int l){
if (l < 0) return false;
for (int i = 0; i < M.size(); ++i) if (M[i] != N[l + i]) return false;
return true;
}
bool check2(int l, int d) {
if (l < 0) return false;
for (int i = 0; i + 1 < M.size(); ++i) if (M[i] != N[l + i]) return false;
if (d != M.back()) return false;
return true;
}
string solve2(){
M = "";
for (int x = m; x; x/= 10) M += (x % 10);
reverse(M.begin(), M.end());
if (N.size() < M.size()) {
return M;
}
string res = N;
vector<bool> f(N.size(), 0);
for (int i = 0; i < N.size(); ++i) {
f[i] = (i ? f[i - 1] : 0) | check1(i - (int)M.size() + 1);
}
for (int i = (int)N.size() - 1; i >= 0; --i) {
for (int d = N[i] + 1; d < 10; ++d) {
if ((i && f[i - 1]) || check2(i - (int)M.size() + 1, d)) {
res[i] = d;
for (int k = i + 1; k < res.size(); ++k) res[k] = 0;
return res;
}
if (i + M.size() < N.size()) {
res[i] = d;
for (int k = i + 1; k < N.size() - M.size(); ++k) res[k] = 0;
for (int k = N.size() - M.size(); k < N.size(); ++k) res[k] = M[k - (N.size() - M.size())];
return res;
}
}
}
return "";
}
string chkmin(string ans1, string ans2) {
if (ans1 == "") return ans2;
if (ans2 == "") return ans1;
if (ans1.size() < ans2.size()) return ans1;
if (ans2.size() < ans1.size()) return ans2;
for (int i = 0; i < ans1.size(); ++i) {
if (ans1[i] < ans2[i]) return ans1;
if (ans2[i] < ans1[i]) return ans2;
}
return ans1;
}
string solve3(){
string ret = "";
for (int i = (int)N.size() - (int)M.size(); i >= 0 && i >= (int)N.size() - (int)M.size() * 2; --i) {
int p = i;
string res = N;
bool ok = true, flg = false;
for (int j = 0; j < M.size(); ++j, ++p) {
if (!flg && M[j] < N[p]) {
ok = false;
break;
}
res[p] = M[j];
if (res[p] > N[p]) flg = true;
}
// cout << i << " "; print(res); cout << " ok = " << ok << " " << flg << endl;
if (ok && flg) {
for (; p < res.size(); ++p) res[p] = 0;
ret = chkmin(ret, res);
}
}
return ret;
}
inline void solve(){
cin >> N >> m;
for (int i = 0; i < N.size(); ++i) N[i] -= '0';
string ans1 = solve1();
string ans2 = solve2();
string ans3 = solve3();
print(chkmin(ans3, chkmin(ans1, ans2)));
}
int main(){
int T;
for (cin >> T; T--; solve());
return 0;
}