rt
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define maxn 1000005
struct Bigint {
int a[maxn], len;
Bigint (int x = 0) {
memset(a, 0, sizeof(a));
for (len = 0; x != 0; x /= 10) a[++len] = x % 10;
}
void flatten(int l) {
len = l;
for (int i = 1; i <= len; i++) {
a[i + 1] += a[i] / 10;
a[i] %= 10;
}
while (!a[len]) len--;
}
int find(int x) {
int sum = 0;
for (int i = 1; i <= len; i++) if (a[i] - '0' == x) sum++;
return sum;
}
};
int n, t, a;
Bigint operator*(Bigint a, int b) {
Bigint c;
int len = a.len;
for (int i = 1; i <= len; i++) c.a[i] = a.a[i] * b;
c.flatten(len + 11);
return c;
}
signed main() {
cin >> t;
for (int i = 1; i <= t; i++) {
cin >> n >> a;
Bigint pro = 1;
for (int j = 1; j <= n; j++) pro = pro * j;
cout << pro.find(a) << endl;
}
return 0;
}