#include<queue>
#include<iostream>
#include<vector>
#include<math.h>
#include<cstring>
using namespace std;
vector<int>primes;
void makeprimes() {
primes.push_back(2);
for (int i = 3; i < 100; i += 2) {
bool fg = true;
for (int j = 0; j<primes.size()&&primes[j] <= sqrt(i); j++) {
if (i%primes[j] == 0) {
fg = false;
break;
}
}
if (fg) {
primes.push_back(i);
}
}
}
bool isPrime(int n) {
for (int i = 0; i < primes.size() && primes[i] <= sqrt(n); i++) {
if (n%primes[i] == 0) {
return 0;
}
}
return 1;
}
void BFS(int a,int b) {
queue<int>q;
int cost[10000];
memset(cost, -1, sizeof(cost));
q.push(a);
cost[a] = 0;
while (!q.empty()) {
int now = q.front();
q.pop();
int gewei = now % 10;
int shiwei = int(now / 10)%10;
int baiwei = int(now / 100) % 10;
int qianwei = int(now / 1000);
int costnow = cost[now];
if (now == b) {
cout<<costnow<<endl;
return;
}
for (int i = 1; i < 10; i++) {//千位
if (i == qianwei)
continue;
int temp = i * 1000 + baiwei * 100 + shiwei * 10 + gewei;
if (cost[temp] == -1 && isPrime(temp)) {
cost[temp] = costnow + 1;
q.push(temp);
}
}
for (int i = 0; i < 10; i++) {//百位
if (i == baiwei)
continue;
int temp = qianwei * 1000 + i * 100 + shiwei * 10 + gewei;
if (cost[temp] == -1 && isPrime(temp)) {
cost[temp] = costnow + 1;
q.push(temp);
}
}
for (int i = 0; i < 10; i++) {//十位
if (i == shiwei) {
continue;
}
int temp = qianwei * 1000 + baiwei * 100 + i * 10 + gewei;
if (cost[temp] == -1 && isPrime(temp)) {
cost[temp] = costnow + 1;
q.push(temp);
}
}
for (int i = 1; i < 10; i += 2) {//个位
if (i == gewei) { continue; }
int temp = qianwei * 1000 + baiwei * 100 + shiwei * 10 + i;
if (cost[temp] == -1 && isPrime(temp)) {
cost[temp] = costnow + 1;
q.push(temp);
}
}
}
}
int main()
{
int a, b;
int n;
cin >> n;
makeprimes();
while (n--) {
cin >> a >> b;
BFS(a, b);
}
return 0;
}