// usename: lxylluvio
// Date: 2022/03/09 10:06
// Remote Judge from Luogu.
#include <iostream>
#include <cstring>
#include <cstdio>
#define st(f,x) memset (f, x, sizeof f);
using namespace std;
bool b[210];
inline void sieve(bool *array, int size = 200) {
b[1] = true;
for (int i = 2; i < 15; i ++)
if (! b[i])
for (int j = i * i; j < size; j += i)
b[j] = true;
}
inline long long calc(long long x) {
if (! x) return 0;
const int N = 30, M = 210;
int c[N], n = 0;
for (; x; x /= 10) c[++ n] = x % 10;
for (int i = 1, j = n; i < j; i ++, j --) swap (c[i], c[j]);
long long f[N][M];
int sum = 0;
long long res = 0;
for (int i = 1; i <= n; i ++) {
for (int j = 0; j < c[i]; j ++) {
st(f, 0);
f[i][sum + j] = 1;
for (int k = i + 1; k <= n; k ++)
for (int l = 0; l <= 9 * (k - 1); l ++)
if (f[k - 1][l])
for (int h = 0; h < 10; h ++)
f[k][h + l] += f[k - 1][l];
for (int k = 2; k <= n * 9; k ++)
if (! b[k])
res += f[n][k];
}
sum += c[i];
}
return res + ! b[sum];
}
signed main() {
sieve(b);
int t;
cin >> t;
while (t --) {
long long l, r;
cin >> l >> r;
cout << calc(r) - calc(l - 1) << '\n';
}
return 0;
}
10-27