import math
# global variables
mainQueue = []
visited = {}
depth = 0
# if num is Sosu return True else False
def isSosu(num):
for i in range( 1, int(math.sqrt(num))+1 ):
if i == 1 :
continue
if num % i == 0 :
return False
return True
# if push number and index, make that index area number 0
def makeOneNumberZero(num, index):
_sub_num = 0
for i in range(4):
if i == index:
continue
else :
_sub_num += ((num / pow(10, i)) % 10 ) * pow(10, i)
return _sub_num
# one round of BFS
def oneRound(numA, numB):
global depth
global mainQueue
subQueue = []
depth += 1
# pop value of Queue while mainQueue doesn't have any element
while len(mainQueue) > 0 :
popedData = mainQueue.pop(0)
# search one node's child
for i in range(4):
subNum = makeOneNumberZero(popedData, i)
for k in range(10):
changedNum = k * pow(10, i) + subNum
if changedNum != numA and changedNum > 1000 and isSosu(changedNum) == True:
# if two num is equal, return depth
if changedNum == numB:
return depth
# if that number is already visited, skip!
elif changedNum in visited.keys():
continue
else :
# make visited site
visited[changedNum] = 1
subQueue.append(changedNum)
return subQueue
# find minimum depth
def findMinChangeNum(numA , numB):
global mainQueue
# if numA and num B is equal when starting time, return 0
if numA == numB :
print '0'
return
while True:
# get one Round return value
answer = oneRound(numA, numB)
# if answer is integer , it is depth!
if type(answer) == int:
print answer
return
else :
# if answer is [] , there is no next number
if answer == [] :
print 'Impossible'
return
# mainQueue change and ready to next Round
else :
mainQueue = answer
# main is start!!
input_text = raw_input().strip('\r').strip('\n').split(' ')
total_num = int(input_text[0])
for i in range(total_num):
input_text = raw_input().strip('\r').strip('\n').split(' ')
mainQueue = [ int(input_text[0]) ]
depth = 0
visited = {}
findMinChangeNum( int(input_text[0]), int(input_text[1]) )