//判断条件写错了,导致没结果,然后就是最高位不能为0,否则会导致结果出错.... Both numbers are four-digit primes (without leading zeros)......
/*思路:因为要找最少变换素数次数,
所以,用bfs解,每次每位由0-9选择,
存入队列,直到符合最终结果,
此时步数为最短步数*/
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<algorithm>
#include<queue>
using namespace std;
const int N = 10000;
bool prime[N];
struct node{
int a;
int step;
node(){
a = 0;
step = 0;
}
node(int ta, int tb){
a = ta;
step = tb;
}
};
queue<node> q;
void SetPrime()//素数判定
{
memset(prime, true, sizeof(prime));
for(int i=2; i<sqrt(N); i++){
for(int j=i*i; j<N; j += i){
prime[j] = false;
}
}
}
void BFS(int s, int e)
{
bool vis[N];
memset(vis, false, sizeof(vis));
vis[s] = true;
while(!q.empty()){
node tmp = q.front();
q.pop();
if(tmp.a == e){//结束条件
cout << tmp.step << endl;
return;
}
for(int i=0; i<4; i++){//位数:个十百千
for(int j=0; j<10; j++){//要变为的数
node tmp2;
if(i == 3 && j == 0)
j++;
int CO = pow(10, i+1);//进位
int mod = pow(10, i);//模数
// cout << CO << " "<< mod << endl;
tmp2.a = tmp.a/CO*CO+j*mod+(tmp.a)%mod;
// cout << tmp.a/pow(10, i+1)*pow(10, i+1) << " "<< j*pow(10, i) << " " <<(tmp.a)%mod << endl;
// cout << tmp.a << " "<< tmp2.a << endl;
if(prime[tmp2.a] && !vis[tmp2.a]){//是素数并且未被拜访过
// cout << tmp.a << endl;
// cout << tmp2.a << endl;
vis[tmp2.a] = true;//标记已被拜访过
tmp2.step = tmp.step+1;//步数加一
q.push(tmp2);
}
}
}
}
}
int main()
{
SetPrime();
int n, st, ed;
cin >> n;
while(n--){
//以防万一,先清空吧
while(!q.empty()){
q.pop();
}
cin >> st >> ed;
node tmp(st, 0);
q.push(tmp);
BFS(st, ed);
}
return 0;
}