Analysis:
This is between 1000-10000, from one prime number to another. We will think of printing the prime number table first and then searching.
In addition, we should transform the prime number. Use queue for storage.
The Code is as follows:
[Cpp]
# Include <cstdio>
# Include <cmath>
# Include <queue>
# Include <cstring>
Using namespace std;
Int k, m;
Int a [4] = };
Int visit [10000], prime [10000];
Void get_prime () // Number of prime numbers in the table
{
Int I, j;
For (I = 2; I <= 10000; I + = 2 ){
Prime [I] = 1;
}
Int N = (int) sqrt (10000.0 );
For (I = 3; I <= N; I + = 2 ){
If (! Prime [I])
For (j = I * I; j <10000; j + = 2 * I)
Prime [j] = 1;
}
}
Int prime_BFS ()
{
Queue <int> Q;
Q. push (k );
Visit [k] = 0;
While (! Q. empty ())
{
Int s = Q. front ();
Q. pop ();
If (s = m) return visit [s];
For (int I = 0; I <4; I ++)
{
For (int j = 0; j <10; j ++)
{
Int x = s/(a [I] * 10); // This conversion is good. Refer to the code of Niu Ren.
Int y = s % a [I];
Int num = x * a [I] * 10 + j * a [I] + y;
If (num> 1000 & visit [num] =-1 &&! Prime [num]) // num> 1000 exclude the first zero.
{
Q. push (num );
Visit [num] = visit [s] + 1;
}
}
}
}
Puts ("Impossible ");
}
Int main ()
{
Int n;
Get_prime ();
While (scanf ("% d", & n )! =-1)
While (n --)
{
Memset (visit,-1, sizeof (visit ));
Scanf ("% d", & k, & m );
// If (! Prime [k] &! Prime [m]);
Printf ("% d \ n", prime_BFS ());
}
Return 0;
}
# Include <cstdio>
# Include <cmath>
# Include <queue>
# Include <cstring>
Using namespace std;
Int k, m;
Int a [4] = };
Int visit [10000], prime [10000];
Void get_prime () // Number of prime numbers in the table
{
Int I, j;
For (I = 2; I <= 10000; I + = 2 ){
Prime [I] = 1;
}
Int N = (int) sqrt (10000.0 );
For (I = 3; I <= N; I + = 2 ){
If (! Prime [I])
For (j = I * I; j <10000; j + = 2 * I)
Prime [j] = 1;
}
}
Int prime_BFS ()
{
Queue <int> Q;
Q. push (k );
Visit [k] = 0;
While (! Q. empty ())
{
Int s = Q. front ();
Q. pop ();
If (s = m) return visit [s];
For (int I = 0; I <4; I ++)
{
For (int j = 0; j <10; j ++)
{
Int x = s/(a [I] * 10); // This conversion is good. Refer to the code of Niu Ren.
Int y = s % a [I];
Int num = x * a [I] * 10 + j * a [I] + y;
If (num> 1000 & visit [num] =-1 &&! Prime [num]) // num> 1000 exclude the first zero.
{
Q. push (num );
Visit [num] = visit [s] + 1;
}
}
}
}
Puts ("Impossible ");
}
Int main ()
{
Int n;
Get_prime ();
While (scanf ("% d", & n )! =-1)
While (n --)
{
Memset (visit,-1, sizeof (visit ));
Scanf ("% d", & k, & m );
// If (! Prime [k] &! Prime [m]);
Printf ("% d \ n", prime_BFS ());
}
Return 0;
}