1 #include <iostream>
2 #include <cstdio>
3 #include <cmath>
4 #include <cstring>
5 #include <algorithm>
6 #include <queue>
7 using namespace std;
8 struct node
9 {
10 int x, step;
11 }s,e;
12 int n, m,vis[10010];
13 int shushu(int k)
14 {
15 int t = sqrt(k);
16 for (int i = 2; i <= t; i++)
17 {
18 if (k%i == 0)
19 return 0;
20 }
21 return 1;
22 }
23 void bfs()
24 {
25 node temp, next;
26 queue<node>q;
27 q.push(s);
28 while (!q.empty())
29 {
30 temp = q.front(); q.pop();
31 if (temp.x == m)
32 {
33 printf("%d", temp.step);
34 return;
35 }
36 for (int i = 1; i < 10; i = i + 2)//枚举个位
37 {
38 next.x = (temp.x / 10) * 10 + i;
39 if (next.x != temp.x&&vis[next.x] == 0 && shushu(next.x))
40 {
41 vis[next.x] = 1;
42 next.step = temp.step + 1;
43 q.push(next);
44 }
45 }
46 for (int i = 0; i < 10; i++)//枚举十位
47 {
48 next.x = (temp.x / 100) * 100 + i * 10 + temp.x % 10;
49 if (next.x != temp.x&&vis[next.x] == 0 && shushu(next.x))
50 {
51 vis[next.x] = 1;
52 next.step = temp.step + 1;
53 q.push(next);
54 }
55 }
56 for (int i = 0; i < 10; i++)//枚举百位
57 {
58 next.x = (temp.x / 1000) * 1000 + i * 100+ temp.x % 100;
59 if (next.x != temp.x&&vis[next.x] == 0 && shushu(next.x))
60 {
61 vis[next.x] = 1;
62 next.step = temp.step + 1;
63 q.push(next);
64 }
65 }
66 for (int i = 1; i < 10; i++)//枚举千位
67 {
68 next.x = i*1000 + temp.x % 1000;
69 if (next.x != temp.x&&vis[next.x] == 0 && shushu(next.x))
70 {
71 vis[next.x] = 1;
72 next.step = temp.step + 1;
73 q.push(next);
74 }
75 }
76 }
77 }
78 int main()
79 {
80 int t;
81 scanf("%d",&t);
82 while (t--)
83 {
84 scanf("%d%d",&n,&m);
85 s.x = n;
86 memset(vis, 0, sizeof(vis));
87 vis[n] = 1;
88 s.step = 0;
89 bfs();
90 printf("\n");
91 }
92 return 0;
93 }