打印素数表+ bfs
#include "iostream"
#include "queue"
#include "algorithm"
#include "cstring"
#include "stack"
using namespace std;
bool is_prime(int n) {
for(int i = 2; i*i <= n; i++) {
if(n % i == 0) return false;
}
return true;
}
int pow(int n) {
int sum = 1;
for(int i = 1; i <= n; i++) {
sum *= 10;
}
return sum;
}
bool isP[10005],vis[10005];
int d[10005];
void bfs(int a,int b) {
memset(d,0,sizeof(d));
memset(vis,0,sizeof(vis));
queue<int> q;
while(!q.empty()) q.pop();
q.push(a);
d[a] = 0;
while(!q.empty()) {
int num = q.front();q.pop();
if(num == b) {
cout << d[num] << endl;
return;
}
vis[num] = 1;
for(int j = 1; j <= 9; j++) {
int s = j * 1000 + num % 1000;
if(!vis[s] && isP[s]) {
vis[s] = 1;
d[s] = d[num]+1;
q.push(s);
}
}
for(int j = 0; j <= 9; j++) {
int s = num - num%1000 + num % 100 + j*100;
if(!vis[s] && isP[s]) {
vis[s] = 1;
d[s] = d[num] + 1;
q.push(s);
}
}
for(int j = 0; j <= 9; j++) {
int s = num - num%100 + num % 10 + j*10;
if(!vis[s] && isP[s]) {
vis[s] = 1;
d[s] = d[num] + 1;
q.push(s);
}
}
for(int j = 0; j <= 9; j++) {
int s = num - num%10 + j;
if(!vis[s] && isP[s]) {
vis[s] = 1;
d[s] = d[num] + 1;
q.push(s);
}
}
}
cout << "Impossible" << endl;
return;
}
int main(){
ios::sync_with_stdio(false);
memset(isP,0,sizeof(isP));
for(int i = 1000; i < 10000; i++) isP[i] = is_prime(i);
int T; cin >> T;
while(T--) {
int a,b;
cin >> a >> b;
bfs(a,b);
}
return 0;
}