prime path
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>
#include<vector>
#include<map>
#include<queue>
#include<stack>
#include<math.h>
#include<set>
using namespace std;
typedef long long ll;
int book[10010];
struct node
{
int x, step;
}s, t;
bool prime(int n)
{
for (int i = 2; i * i <= n; i++)
{
if (n % i == 0)
{
return false;
}
}
return true;
}
void bfs(int a, int b)
{
queue<node>q;
s.x = a;
s.step = 0;
book[s.x] = 1;
q.push(s);
while (!q.empty())
{
s = q.front();
for (int i = 1; i <= 9; i = i + 2)
{
int c = s.x / 10 * 10 + i;
if (c == b)
{
printf("%d\n", s.step + 1);
return;
}
if (!book[c] && prime(c))
{
book[c] = 1;
t.x = c;
t.step = s.step + 1;
q.push(t);
}
}
for (int i = 0; i <= 9; i++)
{
int c = s.x / 100 * 100 + i * 10 + (s.x % 10);
if (c == b)
{
printf("%d\n", s.step + 1);
return;
}
if (!book[c] && prime(c))
{
book[c] = 1;
t.x = c;
t.step = s.step + 1;
q.push(t);
}
}
for (int i = 0; i <= 9; i++)
{
int c = s.x / 1000 * 1000 + i * 100 + (s.x % 100);
if (c == b)
{
printf("%d\n", s.step + 1);
return;
}
if (!book[c] && prime(c))
{
book[c] = 1;
t.x = c;
t.step = s.step + 1;
q.push(t);
}
}
for (int i = 1; i <= 9; i++)
{
int c = i * 1000 + (s.x % 1000);
if (c == b)
{
printf("%d\n", s.step + 1);
return;
}
if (!book[c] && prime(c))
{
book[c] = 1;
t.x = c;
t.step = s.step + 1;
q.push(t);
}
}
q.pop();
}
printf("Impossible\n");
return;
}
int main()
{
int t;
cin >> t;
while (t--)
{
int a, b;
memset(book, 0, sizeof(book));
cin >> a >> b;
if (a == b)
{
printf("0\n");
}
else
{
bfs(a, b);
}
}
return 0;
}