#include<iostream>
#include<queue>
#include<cmath>
using namespace std;
int m, n, ans = 9999;
bool vst[10000] = { 0 }, su[10000] = {0};
struct node {
int num; //数
int step; //深度
}now,nex;
queue<node>q;
void sushushai() { //素数筛
for (int i = 1000;i <= 9999;i++) {
int work = 0;
for (int j = 2;j <= sqrt(i);j++) {
if (i % j == 0) { work = 1;break; }
}
if (work == 0)su[i] = 1;
}
}
void bfs() {
if (now.num == n) {
cout << now.step << endl;
return;
}
while (!q.empty()) {
now = q.front(); //now是要进行变化的数
char t[5];
t[1] = now.num / 1000;
t[2] = now.num % 1000 / 100;
t[3] = now.num % 100 / 10;
t[4] = now.num % 10;
for (int i = 1;i <= 4;i++) {
int temp = t[i]; //存一下本位
for (int j = 0;j <= 9;j++) {
if (i == 1 && j == 0)continue; //第一位不能为0
t[i] = j;
nex.num = t[1] * 1000 + t[2] * 100 + t[3] * 10 + t[4];
nex.step = now.step + 1;
if (su[nex.num] == 1 && vst[nex.num] == 0) { //若符合条件则存入队列
if (nex.num == n) { //达到目标则输出当前深度 return
cout << nex.step << endl;
return;
}
vst[nex.num] = 1; //未达到目标则将其存入队列
q.push(nex);
}
}
t[i] = temp; //恢复本位
}
q.pop(); //遍历完成弹出now
}
}
int main() {
sushushai();
int k;
cin >> k;
while (k--) {
//初始化
memset(vst, 0, sizeof(vst));
ans = 0;
q = queue<node>();
cin >> m >> n;
now.num = m;
now.step = 0;
vst[m] = 1;
q.push(now);
bfs();
}
}