// Problem: P1591 阶乘数码
// Contest: Luogu
// URL: https://www.luogu.com.cn/problem/P1591
// Memory Limit: 125 MB
// Time Limit: 1000 ms
// User: Pannnn
#include
using namespace std;
vector mulByI(vector a, int b) {
vector res;
int pre = 0;
for (int i = 0; i < a.size(); ++i) {
pre += a[i] * b;
res.push_back(pre % 10);
pre /= 10;
}
while (pre) {
res.push_back(pre % 10);
pre /= 10;
}
return res;
}
vector getRes(int n) {
vector res(1, 1);
for (int i = 1; i <= n; ++i) {
res = mulByI(res, i);
}
return res;
}
int main() {
int t;
cin >> t;
while (t--) {
int n, a;
cin >> n >> a;
vector res = getRes(n);
long long cnt = 0;
for (auto i : res) {
if (i == a) {
++cnt;
}
}
cout << cnt << endl;
}
return 0;
}