#!/Users/xchen5/opt/anaconda3/bin/python3

import sys
input = sys.stdin.readline

def ri(): return int(input())
def rl(v_type=int): return list(map(v_type, input().split()))
def rs(): return input().rstrip()
def out(x, sep=' '): return sep.join(map(str, x))

INF = float('inf')

def solve_case():
    n, x = rl()

    lim = 1
    for i in range(1, n):
        lim *= 10

    f = {}

    def rec(x):
        if x >= lim:
            return 0
        if x in f:
            return f[x]
        res = INF
        for d in map(int, str(x)):
            if d >= 2:
                res = min(res, 1 + rec(x * d))
        f[x] = res
        return res

    ans = rec(x)
    print(ans if ans != INF else -1)

if __name__ == '__main__':
    T = 1
    # T = ri()
    for ti in range(1, T + 1):
        solve_case()
        # print(f'Case #{ti}: {solve_case()}')

def solve(n, x, dp):
    if len(str(x)) >= n:
        return 0

    if x in dp:
        return dp[x]

    ans = float('inf')

    for i in str(x):
        if i != '1' and i != '0':
            ans = min(ans, 1+solve(n, x*int(i), dp))
            dp[x] = ans
    return ans

n, x = map(int, input().split(' '))
dp = {}

sol = solve(n, x, dp)
print(-1 if sol == float('inf') else sol)

# import sys
# sys.stdin = open('input.txt', 'r')
import math
from collections import deque

n,x =map(int,input().split(" "))
dp={}
dp[x]=0
current=x
lowest=math.inf
nextInLine=deque([x])

while nextInLine:
	if len(str(current))<=n:
		for r in str(current):
			if(r!='1' and r!='0'):
				if not current*int(r) in dp or dp[current*int(r)]>dp[current]+1:
					dp[current*int(r)]=dp[current]+1
					nextInLine.append(current*int(r))
					if(len(str(current*int(r)))==n):
						if(dp[current*int(r)]<lowest):
							lowest=dp[current*int(r)]

	nextInLine.popleft()
	if nextInLine:
		current=nextInLine[0]

if lowest==math.inf:
	print(-1)
else:
	print(lowest)

import collections

def dig(x):
	d = []
	while x>0:
		d.append(x%10)
		x=x//10
	return d

#n = int(input())
#a = list(map(int,input().split()))
n,x = map(int,input().split())

seen = set()
seen.add(x)
q = collections.deque([])
q.append(x)
ops = 0
flag = False

while len(q)>0:

	#print(q)
	for i in range(len(q)):
		curx = q.popleft()
		d = dig(curx)
		if len(d) == n:
			flag = True
			break

		for y in d:
			newx = curx*y
			if newx not in seen:
				q.append(newx)
				seen.add(newx)
	if flag:
		break
	ops+=1

if flag:
	print(ops)
else:
	print(-1)

import collections

n, x = map(int, input().split())
q = collections.deque([])
dist = {x: 0}
q.append(x)
while q:
    k = q.popleft()
    s = str(k)
    if len(s) == n:
        print(dist[k])
        quit()
    for i in s:
        if i == '0':
            continue
        w = k * int(i)
        if dist.get(w, -1) == -1:
            dist[w] = dist[k] + 1
            q.append(w)
print(-1)

#!/usr/bin/env python
import os
import sys
from io import BytesIO, IOBase

BUFSIZE = 8192

class FastIO(IOBase):
  newlines = 0

  def __init__(self, file):
    self._file = file
    self._fd = file.fileno()
    self.buffer = BytesIO()
    self.writable = "x" in file.mode or "r" not in file.mode
    self.write = self.buffer.write if self.writable else None

  def read(self):
    while True:
      b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
      if not b:
        break
      ptr = self.buffer.tell()
      self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)

    self.newlines = 0
    return self.buffer.read()

  def readline(self):
    while self.newlines == 0:
      b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
      self.newlines = b.count(b"\n") + (not b)
      ptr = self.buffer.tell()
      self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
    self.newlines -= 1
    return self.buffer.readline()

  def flush(self):
    if self.writable:
      os.write(self._fd, self.buffer.getvalue())
      self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
  def __init__(self, file):
    self.buffer = FastIO(file)
    self.flush = self.buffer.flush
    self.writable = self.buffer.writable
    self.write = lambda s: self.buffer.write(s.encode("ascii"))
    self.read = lambda: self.buffer.read().decode("ascii")
    self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

def int_1():
  return int(input())

def int_k():
  return map(int, input().split())

def int_l():
  return list(int_k())

def getGraph(start, end, loop):
  graph = {i: [] for i in range(start, end+1)}

  for _ in range(loop):
    u, v = int_k()
    graph[u].append(v)
    graph[v].append(u)

  return graph

def helper(x, lim, dp):
  if x > lim:
    return 0

  if x in dp:
    return dp[x]

  result = float('inf')
  for char in str(x):
    if int(char) >= 2:
      result = min(result, 1 + helper(x * int(char), lim, dp))

  dp[x] = result
  return result

def solve():
  n, x = int_k()

  lim = 1
  for i in range(n-1):
    lim *= 10

  result = helper(x, lim, dict())

  if result == float('inf'):
    print(-1)
    return
  print(result)

for _ in range(1):
  solve()

#!/usr/bin/env python

import sys
import collections
import math

ifs = sys.stdin
ofs = sys.stdout

def numbers_from_line(d=' '):
    return [
        int(s)
        for s in ifs.readline().strip().split(d)
        if len(s.strip()) > 0
    ]

def digits(n):
    D = []
    while n > 0:
        n, d = divmod(n, 10)
        D.append(d)
    return D

def solve(n, x):
    min_steps = math.inf
    seen = set()
    queue = collections.deque([(x, 0)])
    while queue:
        x, steps = queue.popleft()
        dx = digits(x)
        if len(dx) == n:
            min_steps = min(min_steps, steps)
            continue
        if len(dx) > n:
            continue
        dx = set(dx)
        for d in dx:
            if d <= 1:
                continue
            xd = x * d
            if xd in seen:
                continue
            seen.add(xd)
            queue.append((xd, steps + 1))
    if min_steps == math.inf:
        return None
    return min_steps

n, x = numbers_from_line()
a = solve(n, x)
if a is None:
    ofs.write('-1')
else:
    ofs.write(str(a))
ofs.write('\n')

#https://codeforces.com/blog/entry/71884
import sys
input = sys.stdin.readline
from math import inf, gcd, log, log2, floor, ceil, sqrt
from collections import Counter, defaultdict, deque
from heapq import heappush, heappop, heapify
from functools import lru_cache
from itertools import permutations, accumulate
from bisect import insort, bisect_left, bisect_right

############ ---- Input Functions ---- ############
def inp():
    return(int(input()))
def inlt():
    return(list(map(int,input().split())))
def insr():
    s = input()
    return(list(s[:len(s) - 1]))
def invr():
    return(map(int,input().split()))

from random import randint

RANDOM = randint(1, 10 ** 9)

class Wrapper(int):
    def __init__(self, x):
        int.__init__(x)
    def __hash__(self):
        return super(Wrapper, self).__hash__() ^ RANDOM

def solve(n,x):

    if x == 1 and n > 1:
        return -1

    q = deque()
    q.append((x,0))
    visit = set([x])
    while q:
        for _ in range(len(q)):
            ele,dist = q.popleft()
            s = str(ele)
            if len(s) >= n:
                return dist
            t = sorted(list(set(s)),reverse=True)[:4]
            for x in t:
                if x == "0" or x == "1":
                    continue
                num = ele*int(x)
                if num not in visit:
                    q.append((num,dist+1))
                    visit.add(num)

    return -1

d = inlt()
n,x = d[0],d[1]
print(solve(n,x))#

import queue

def solve():
    n, x = [int(x) for x in input().split()]
    minAcc = pow(10, n-1)
    maxAcc = pow(10, n) - 1
    q = queue.Queue()
    q.put((x, 0))
    seen = set()
    while not q.empty():
        top = q.get()
        if top[0] in seen or top[0] > maxAcc:
            continue
        seen.add(top[0])
        if top[0] >= minAcc and top[0] <= maxAcc:
            print(top[1])
            return
        st = str(top[0])
        chars = set()
        for char in st:
            chars.add(char)
        for char in chars:
            num = int(char)
            nex = top[0] * num
            q.put((nex, top[1] + 1))

    print(-1)

solve()

import sys
from bisect import bisect_right, bisect_left
import os
import sys
from io import BytesIO, IOBase
from math import factorial, floor, sqrt, inf, ceil, gcd
from collections import defaultdict, deque, Counter
from functools import cmp_to_key

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

############ ---- Input Functions ---- ############
def inp():
    return(int(input()))
def inlt():
    return(list(map(int,input().split())))
def insr():
    s = input()
    return(s[:len(s) - 1])
def invr():
    return(map(int,input().split()))
def insr2():
    s = input()
    return(s.split(" "))

###functions

### Calculate C(n, r) mod p, where p is prime (fast with precalculation)

def build_mod_inverses(n, r, p):
    fact = [1] * (n + 1)
    for i in range(1, n + 1):
        fact[i] = i * fact[i - 1] % p

    inv = [1] * (n + 1)
    inv[n] = pow(fact[n], p - 2, p)
    for i in range(n - 1, -1, -1):
        inv[i] = (i + 1) * inv[i + 1] % p

    return fact, inv

# fast C(n, r) mod p calculation using predefined fact and inv
def comb(n, r, p, fact, inv):
    return fact[n] * inv[r] % p * inv[n - r] % p if n >= r >= 0 else 0

def make_divisors(n):
    divisors = []
    for i in range(1, int(n**0.5)+1):
        if n % i == 0:
            divisors.append(i)
            if i != n // i and i != 1:
                divisors.append(n // i)
    return divisors

def dfs(graph, vertex):
    visited = set()
    tree = []
    deq = deque([vertex])
    while deq:
        vertex = deq.pop()
        if vertex not in visited:
            visited.add(vertex)
            deq.extend(graph[vertex])
            tree.append(vertex)
    return tree

def find_in_sorted_list(elem, sorted_list):
    # https://docs.python.org/3/library/bisect.html
    'Locate the leftmost value exactly equal to x'
    i = bisect_left(sorted_list, elem)
    if i != len(sorted_list) and sorted_list[i] == elem:
        return i
    return -1

############ SEGMENT TREE ##############

class SegmentTree:
    def __init__(self, data, default=0, func=lambda a, b: a+b):
        """initialize the segment tree with data"""
        self._default = default
        self._func = func
        self._len = len(data)
        self._size = _size = 1 << (self._len - 1).bit_length()

        self.data = [default] * (2 * _size)
        self.data[_size:_size + self._len] = data
        for i in reversed(range(_size)):
            self.data[i] = func(self.data[i + i], self.data[i + i + 1])

    def __delitem__(self, idx):
        self[idx] = self._default

    def __getitem__(self, idx):
        return self.data[idx + self._size]

    def __setitem__(self, idx, value):
        idx += self._size
        self.data[idx] = value
        idx >>= 1
        while idx:
            self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
            idx >>= 1

    def __len__(self):
        return self._len

    def query(self, start, stop):
        if start == stop:
            return self.__getitem__(start)
        start += self._size
        stop += self._size

        res = self._default
        while start < stop:
            if start & 1:
                res = self._func(res, self.data[start])
                start += 1
            if stop & 1:
                stop -= 1
                res = self._func(res, self.data[stop])
            start >>= 1
            stop >>= 1
        return res

    def __repr__(self):
        return "SegmentTree({0})".format(self.data)

###code

n, x = inlt()
depth = 0
start = (x, depth)
visited = set()

if set(str(x)) == set('1') or set(str(x)) == set('0') or set(str(x)) == set(['1', '0']):
    print(-1)
    sys.exit()

deq = deque([start])
while deq:
    vertex = deq.popleft()
    if vertex not in visited:
        visited.add(vertex)
        if len(str(vertex[0])) >= n:
            print(vertex[1])
            sys.exit()

        for num in str(vertex[0]):
            val = vertex[0] * int(num)
            depth = vertex[1]+1
            deq.append((val, depth))

def element(x):
    se = set()
    while x:
        se.add(x%10)
        x//=10
    return se

n,x = map(int,input().split())
if n<len(str(x)):
    print(-1)
elif n==len(str(x)):
    print(0)
else:
    dic = {}
    dic[x]=0
    cond = True
    ans = 10**20
    while cond:
        if len(dic)==0:
            break
        dic_2={}
        #print(dic)
        for ele in dic.keys():
            for se in element(ele):
                if se==1 or se==1:
                    continue

                if len(str(se*ele))>=n:
                    ans = min(ans,dic[ele]+1)
                    cond = False
                    break

                dic_2[se*ele] = dic[ele]+1
                if cond==False:
                    break

            if cond==False:
                break
        dic = dic_2
    if ans==10**20:
        print(-1)
    else:
        print(ans)

from collections import deque as Queue

n, x = map(int, input().split())

ans = 10**18
que = Queue()
que.append((str(x), 0))
st = set()
while que:
   now, cnt = que.pop()
   if len(now) == n:
      ans = cnt
      break

   for c in ''.join(set(now)):
      nxt = str(int(now) * int(c))
      if (len(nxt) > n):
         continue
      if int(nxt) in st:
         continue
      que.appendleft((nxt, cnt + 1))
      st.add(int(nxt))

print('-1' if ans == 10**18 else ans)

import sys, io, os

input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

cache = {}

def digits(x):
    digits = sorted([int(digit) for digit in set([ch for ch in str(x)])])
    return digits

def count_operations(n, x):
    cached = cache.get(x)
    if cached:
        return cached

    str_x = str(x)
    if len(str_x) == n:
        return 0

    min_op = float("inf")
    for d in digits(x):
        if d < 2:
            continue

        min_op = min(min_op, 1 + count_operations(n, x * d))

    cache[x] = min_op
    return min_op

n, x = map(int, input().split())
c = count_operations(n, x)
if c == float("inf"):
    c = -1
sys.stdout.write(f"{c}\n")

(n, x) = map(int, input().split())

q = [(x, 0)]

maxlen = {}

succ = 0

ans = float('inf')

goal = 10 ** (n - 1)

while len(q) > 0:
    (num, ops) = q.pop(-1)
    if ops >= ans:
        continue
    if num >= goal:
        ans = ops
        continue
    # print(ori, l, ops)
    need = 0
    tmp = num
    while tmp < goal:
        tmp *= 9
        need += 1
    if need + ops >= ans:
        continue
    appeared = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    tmp = num
    while tmp > 0:
        appeared[tmp % 10] = 1
        tmp //= 10
    for digit in range(9, 1, -1):
        if appeared[digit] == 1:
            q.append((num * digit, ops + 1))

if ans == float('inf'):
    print(-1)
else:
    print(ans)

from math import inf

def has_digit(x, i):
    while x > 0:
        if x%10 == i:
            return True
        x //= 10
    return False

def num_len(x):
    res = 0
    while x > 0:
        res += 1
        x //= 10
    return res

dp = {}
# n = target length
# x = cur number
# dp = 10-d list
# dp[1][1][1][1][1][1]...
def dumb(n, x, state: tuple):
    global dp
    if num_len(x) == n:
        return 0
    if state in dp:
        return dp[state]

    ans = inf
    new_state = list(state)
    for i in range(2,10):
        if not has_digit(x, i):
            continue

        mult = i
        for idx, fac in enumerate((2, 3, 5, 7)):
            while mult%fac == 0:
                new_state[idx] += 1
                mult //= fac

        ans = min(ans, 1+dumb(n, x*i, tuple(new_state)))
        new_state = list(state)

    dp[state] = ans
    return ans

n, x = [int(x) for x in input().split()]
ans = dumb(n,x,(0,0,0,0))
print(-1 if ans == inf else ans)

import io,os
from collections import deque

input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def main(t):

    n,x = map(int,input().split())

    queue = deque()
    queue.append([str(x),0])
    dic = {}

    while queue:
        s,step = queue.popleft()
        for c in s:
            nexts = str(int(s)*int(c))
            if len(nexts)==n:
                print(step+1)
                return
            if nexts in dic:  continue
            dic[nexts] = 1
            queue.append([nexts,step+1])

    print(-1)

T = 1 #int(input())
t = 1
while t<=T:
    main(t)
    t += 1

import os
import sys
from io import BytesIO, IOBase

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

from collections import deque

n, x = map(int, input().split())

oklow = 10**(n - 1)
def ok(e):
    return oklow <= e

if x == "1":
    print("-1")
else:
    Q = deque([(x, 0)])
    V = {}
    r = 1000000
    while Q:
        e, d = Q.pop()

        if ok(e):
            r = min(r, d)
        elif e not in V or V[e] > d:
            V[e] = d

            vr = e
            mask = 0
            while vr != 0:
                m = vr % 10
                if m > 1 and (mask & (1 << m) == 0):
                    Q.append((e * m, d + 1))
                mask |= (1 << m)
                vr //= 10

    print(r if r < 1000000 else -1)

n, x = map(int, input().split())
from collections import deque
Q = deque()
dp = {}
dp[x] = 0
Q.append(x)

def length(p):
  ans = 0
  while p:
    ans += 1
    p //= 10
  return ans

yesCase = 0

while Q:
  u = Q.popleft()
  if length(u) == n:
    print(dp[u])
    yesCase = 1
    break
  v = u
  st = set()
  while v:
    st.add(v % 10)
    v //= 10
  vt = list(st)
  for i in range(len(vt)):
    curr = u * vt[i]
    if curr not in dp:
    #   if length(curr) < dp[u]:
    #     continue
      dp[curr] = dp[u] + 1
      Q.append(curr)
if yesCase == 0:
  print(-1)

# author: ankan2526

import sys,math
input = sys.stdin.readline
sys.setrecursionlimit(10**5)

ints = lambda : list(map(int,input().split()))
#def gprint(t,ans=''): print(f"Case #{t+1}:",*ans)
p = 10**9+7
inf = 10**20+7
#alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
#p2 = [1]
#for i in range(70):p2.append(p2[-1]*2)
#ANS=[]

def check(n,x):
    if len(str(x))==n:
        return 0
    if x in dp:
        return dp[x]
    ans = p
    for i in str(x):
        if int(i)>1:
            z = check(n,x*int(i))+1
            if z!=0:
                ans = min(ans,z)
    if ans==p:
        ans=-1
    dp[x] = ans
    return ans

n,x = ints()
dp = {}
print(check(n,x))

import sys
input = sys.stdin.readline
from collections import *

def dfs(now):
    global ans

    if memo[now]!=-1:
        return memo[now]

    if now>=low:
        return 0

    s = set()
    t = now

    while t:
        d = t%10
        t //= 10

        if d>1:
            s.add(d)

    res = 100

    for d in s:
        res = min(res, 1+dfs(now*d))

    memo[now] = res
    return res

n, x = map(int, input().split())
low = pow(10, n-1)
ans = 10**18
memo = defaultdict(lambda: -1)
ans = dfs(x)

if ans==100:
    print(-1)
else:
    print(ans)

from collections import deque
n,x=map(int,input().split())
q=deque()
dist={}
dist[x]=0
q.append(x)
while q:
    p=q.popleft()
    if len(str(p))==n:
        print(dist[p])
        exit()
    else:
        for el in str(p):
            if el!="0":
                w=p*int(el)
                if w  not in dist:
                    dist[w]=dist[p]+1
                    q.append(w)
print(-1)
exit()

n, x = input().split()
n = int(n)
yy = set([int(w) for w in list(x)])
x = int(x)
# print(yy)
# ans = n * 10
# for y in yy:
#     if y == 1:
#         continue
#     cnt = 0
#     cur = x
#     while len(str(cur)) < n:
#         cur = cur * y
#         cnt += 1
#         if len(str(cur)) > n:
#             break
#     if len(str(cur)) == n:
#         if ans > cnt:
#             ans = cnt
Q = []
Q.append((x, 0))
dic = {}
while len(Q) > 0:
    tee = Q[0]
    # print(tee)
    Q.pop(0)
    yy = set([int(w) for w in list(str(tee[0]))])
    # yy = [max(yy)]
    # print(yy)
    for y in yy:
        if y == 1:
            continue
        cur = tee[0] * y
        if len(str(cur)) == n:
            print(tee[1] + 1)
            exit()
        if len(str(cur)) < n:
            if cur in dic.keys():
                if tee[1] + 1 < dic[cur]:
                    Q.append((cur, tee[1] + 1))
                    dic[cur] = tee[1] + 1
            else:
                Q.append((cur, tee[1] + 1))
                dic[cur] = tee[1] + 1

# if ans == n * 10:
print('-1')
# else:
    # print(ans)

import collections
def get_len(n):
    res=  0
    while n:
        res += 1
        n //= 10
    return res
def bfs(start, d, n):
    q = collections.deque()
    q.append(start)
    d[start] = 0
    while len(q) > 0:
        v = q.popleft()
        if get_len(v) == n:
            return d[v]
        vv = v
        while vv:
            to = v * (vv % 10)
            if to >= 10 ** n or to in d:
                vv //= 10
                continue
            d[to] = d[v] + 1
            q.append(to)
            vv //= 10
    return -1

def solve():
    n, x = map(int, input().split())
    d = dict()
    print(bfs(x, d, n))

for _ in range(1):
    solve()

import sys, random
from collections import defaultdict

class DefaultDict:
    def __init__(self, default=None):
        self.default = default
        self.x = random.randrange(1, 1 << 31)
        self.dd = defaultdict(default)

    def __repr__(self):
        return "{"+", ".join(f"{k ^ self.x}: {v}" for k, v in self.dd.items())+"}"

    def __eq__(self, other):
        return set(self.dd.items()) == set(other.dd.items())

    def __or__(self, other):
        res = DefaultDict(self.default)
        for k, v in self.dd: res[k] = v
        for k, v in other.dd: res[k] = v
        return res

    def __len__(self):
        return len(self.dd)

    def __getitem__(self, item):
        return self.dd[item ^ self.x]

    def __setitem__(self, key, value):
        self.dd[key ^ self.x] = value

    def __delitem__(self, key):
        del self.dd[key ^ self.x]

    def __contains__(self, item):
        return item ^ self.x in self.dd

    def items(self):
        for k, v in self.dd.items(): yield (k ^ self.x, v)

    def keys(self):
        for k in self.dd: yield k ^ self.x

    def values(self):
        for v in self.dd.values(): yield v

    def __iter__(self):
        for k in self.dd: yield k ^ self.x

class Counter(DefaultDict):
    def __init__(self, aa=[]):
        super().__init__(int)
        for a in aa: self.dd[a ^ self.x] += 1

    def __add__(self, other):
        res = Counter()
        for k, v in self.items(): res[k] = v
        for k, v in other.items(): res[k] += v
        return res

    def __sub__(self, other):
        res = Counter()
        for k, v in self.items(): res[k] = v
        for k, v in other.items(): res[k] -= v
        return res

    def __and__(self, other):
        res = Counter()
        for k in self:
            v = min(self[k], other[k])
            if v > 0: res[k] = v
        return res

    def __or__(self, other):
        res = Counter()
        for k in set(self) | set(other):
            v = max(self[k], other[k])
            if v > 0: res[k] = v
        return res

    def __iter__(self):
        for k in self.dd: yield k ^ self.x

class Set:
    def __init__(self, aa=[]):
        self.x = random.randrange(1, 1 << 31)
        self.st = set()
        for a in aa: self.st.add(a ^ self.x)

    def __repr__(self):
        return "{"+", ".join(str(k ^ self.x) for k in self.st)+"}"

    def __len__(self):
        return len(self.st)

    def add(self, item):
        self.st.add(item ^ self.x)

    def discard(self, item):
        self.st.discard(item ^ self.x)

    def __contains__(self, item):
        return item ^ self.x in self.st

    def __iter__(self):
        for k in self.st: yield k ^ self.x

    def pop(self):
        return self.st.pop() ^ self.x

    def __or__(self, other):
        res = Set(self)
        for a in other: res.add(a)
        return res

    def __and__(self, other):
        res = Set()
        for a in self:
            if a in other: res.add(a)
        for a in other:
            if a in self: res.add(a)
        return res

# sys.setrecursionlimit(200005)
int1 = lambda x: int(x)-1
pDB = lambda *x: print(*x, end="\n", file=sys.stderr)
p2D = lambda x: print(*x, sep="\n", end="\n\n", file=sys.stderr)
def II(): return int(sys.stdin.readline())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def LI1(): return list(map(int1, sys.stdin.readline().split()))
def LLI1(rows_number): return [LI1() for _ in range(rows_number)]
def SI(): return sys.stdin.readline().rstrip()
dij = [(0, 1), (-1, 0), (0, -1), (1, 0)]
# dij = [(0, 1), (-1, 0), (0, -1), (1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)]
inf = (1 << 63)-1
# inf = 4294967295
# md = 10**9+7
# md = 998244353

from collections import deque

def size(a):
    return len(str(a))

def solve():
    n, x = LI()

    if size(x) > n:
        print(-1)
        return

    q = deque()
    q.append((x, 0))
    fin = set()
    while q:
        a, c = q.popleft()
        for d in set(list(int(c) for c in str(a))):
            if d < 2: continue
            b = a*d
            s = size(b)
            if s == n:
                print(c+1)
                return
            if s > n or b in fin: continue
            fin.add(b)
            q.append((b, c+1))
    print(-1)

    # ***************************************

# testnumber = II()
testnumber = 1
for testcase in range(testnumber):
    solve()
    # print("YES" if solve() else "NO")

def solve(n, x):
    q, dist = [], {}
    dist[x] = 0
    q.insert(0, x)
    while q != []:
        k = q.pop()
        s = str(k)
        if len(s) == n:
            return dist[k]
        for x in s:
            if x != '0':
                w = k * int(ord(x) - ord('0'))
                if dist.get(w) == None:
                    dist[w] = dist[k]+1
                    q.insert(0, w)
    return -1

if __name__ == '__main__':
    n, x = list(map(int, input().split()))
    print(solve(n, x))

from io import BytesIO
from os import fstat, read
# input = BytesIO(read(0, fstat(0).st_size)).readline
I = lambda:[*map(int,input().split())]

# INT       -    int(input())
# INT LIST  -    [*map(int,input().split())]
# STRING    -    input().decode("UTF-8")[:-2]
# STRING    -    input().decode("UTF-8").split()
################################################################################
from collections import deque
# from itertools import combinations, permutations
# from math import ceil
# import heapq

n, x = I()
q = deque()
q.append(x)
dist = {x : 0}
while q:
	num = q.popleft()
	s = str(num)
	if len(s) == n:
		print(dist[num])
		break
	for i in range(9, 1, -1):
		if str(i) in s:
			num2 = i * num
			if num2 not in dist:
				dist[num2] = dist[num] + 1
				q.append(num2)
else:
	print(-1)

from functools import lru_cache
n,x = list(map(int,input().split()))

@lru_cache(maxsize=None)
def dp(nn,xx):
	y = str(xx)
	if len(y)==nn:
		return 0
	res = 1e9
	for j in y:
		if int(j)>1:
			res = min(res,1 + dp(nn,xx*int(j)))
	return res

res = dp(n,x)
if res>=1e9:
	print(-1)
else:
	print(res)

from collections import deque
n,x = map(int,input().split(' '))

q = deque()
q.append(x)
dist = {x: 0}
ans = -1
while len(q) > 0:
    num = q.popleft()
    s = str(num)
    if len(s)==n:
        ans = dist[num]
        break
    for d in range(2,10):
        if str(d) in s:
            num2 = num*d
            if num2 not in dist:
                dist[num2] = dist[num]+1
                q.append(num2)
print(ans)

from collections import deque as Queue

n, x = map(int, input().split())

ans = 10**18
que = Queue()
que.append((str(x), 0))
st = set()
while que:
   now, cnt = que.pop()
   if len(now) == n:
      ans = cnt
      break

   for c in ''.join(set(now)):
      nxt = str(int(now) * int(c))
      if (len(nxt) > n):
         continue
      if int(nxt) in st:
         continue
      que.appendleft((nxt, cnt + 1))
      st.add(int(nxt))

print('-1' if ans == 10**18 else ans)

from collections import *
import sys
import io, os
import math
import random
from heapq import *
gcd = math.gcd
sqrt = math.sqrt
def ceil(a, b):
    a = -a
    k = a // b
    k = -k
    return k
# arr=list(map(int, input().split()))
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def strinp(testcases):
    k = 5
    if (testcases == -1 or testcases == 1):
        k = 1
    f = str(input())
    f = f[2:len(f) - k]
    return f

def cleanarr(arr):
    n = len(arr)
    #  put comment if arr already sorted
    arr.sort()
    c = [[1, arr[0]]]
    k = 0
    for i in range(n - 1):
        if (arr[i] != arr[i + 1]):
            c.append([1,arr[i + 1]])
            k += 1
        else:
            c[k][0] += 1
    return c

def main():
    t=1
    for _ in range(t):
        arr=list(map(int, input().split()))
        n=arr[0]
        x=arr[1]
        if(len(str(x))==n):
            print(0)
            continue
        dic={}
        dic[x]=1
        c=0
        while(True):
            c+=1
            ndic={}
            ma=0
            for j in dic:
                s=str(j)
                for k in s:
                    if(int(k)>1):
                        f=True
                        ndic[int(k)*j]=1
                        ma=max(ma,int(k)*j)
            if(ma==0):
                c=-1
                break
            if(len(str(ma))==n):
                break
            dic=ndic
        print(c)

main()

def brute(n, x):
    if n == len(str(x)):
        return 0
    if (n, x) in memo:
        return memo[(n, x)]
    ans = 10**9
    for ch in str(x):
        if ch=='0' or ch=='1': continue
        ans = min(ans, 1 + brute(n, x*int(ch)))
    memo[(n, x)] = ans
    return ans

nc, xc = map(int, input().split())

# n, x = nc, xc
#
# moves = 0
#
# while len(str(x)) < n:
#     d = max(list(str(x)))
#     if d == '0' or d=='1':
#         moves = -1
#         break
#     x = x * int(d)
#     moves += 1
#
# print(moves)
#
memo = {}
res = brute(nc, xc)

if res >= 10**9:
    print(-1)
else:
    print(res)

import copy
import gc
import itertools
from array import array
from fractions import Fraction
import heapq
import math
import operator
import os, sys
import profile
import cProfile
import random
import re
import string
from bisect import bisect_left, bisect_right
from collections import defaultdict, deque, Counter
from functools import reduce, lru_cache
from io import IOBase, BytesIO
from itertools import count, groupby, accumulate, permutations, combinations_with_replacement, product
from math import gcd
from operator import xor, add
from typing import List

# region fastio
BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._file = file
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

# print = lambda d: sys.stdout.write(str(d)+"\n")
def read_int_list(): return list(map(int, input().split()))
def read_int_tuple(): return tuple(map(int, input().split()))
def read_int(): return int(input())

# endregion

### CODE HERE

# f = open('inputs', 'r')
# def input(): return f.readline().rstrip("\r\n")

# sys.setrecursionlimit(10000)

def solve(n, x):
    sx = str(x)
    if len(sx) == n: return 0

    if set(sx).issubset({'0', '1'}):
        return -1

    q = deque([(0, x)])
    seen = {x}
    while q:
        dist, y = q.popleft()
        sy = str(y)
        if len(sy) == n:
            # print(y)
            return dist
        for d in map(int, set(sy)):
            if d in (0, 1): continue
            z = y * d
            if z in seen: continue
            seen.add(z)
            q.append((dist + 1, z))

def main():
    for _ in range(1):
        n, x = read_int_tuple()
        print(solve(n, x))

if __name__ == "__main__":
    main()
# cProfile.run("main()")

from ast import Return
import sys,io,os
from os import path
from collections import Counter,defaultdict
if(path.exists('input.txt')):
     sys.stdin = open('input.txt','r')
     sys.stdout = open('output.txt','w')
else:
     input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline

def highes(cur,n,mem):
     if len(str(cur))==n:
          return 0
     if cur in mem:
          return mem[cur]
     now=1e16
     for i in str(cur):
          if i=='1' or i=='0':
               continue
          now=min(now,highes(cur*int(i),n,mem)+1)
    # print(cur,n,now)
     mem[cur]=now
     return now
def main():
#     n=int(input())
     n,x=list(map(int,input().split()))
     if n<len(str(x)):
          print(-1)
          Return
     if n==len(str(x)):
          print(0)
          return
     mem={}
     x=highes(x,n,mem)
     if x==1e16:
          print(-1)
          return
     print(x)

for _ in range(1):
    main()

import sys
from functools import lru_cache
inf=float('inf')
n,x=[int(i) for i in input().split()]
low=10**(n-1)
high=10**n
@lru_cache(None)
def fun(x,n):
    s=set(str(x))
    if len(s)==1 and '1' in s:
        return inf
    ans=inf

    for i in s:
        i=int(i)
        if low<=x<high:
            ans=min(ans,0)
        if x<low and i>=2:
            ans=min(ans,1+fun(x*i,n))
    return ans
ans=fun(x,n)
if ans==inf:
    print(-1)
else:
    print(ans)

from collections import deque

n, x = [int(x) for x in input().split()]

q = deque()
q.append((x, 0))
ans = -1

mp = {x: 0}

while q:
    num, t = q.popleft()
    snum = str(num)
    l = len(snum)
    if l == n:
        ans = t
        break
    for s in snum:
        y = int(s)
        if y == 0:
            continue
        res = num * y
        if not (res in mp):
            mp[res] = t + 1
            q.append((res, t + 1))
print(ans)

import sys
import os
from io import BytesIO, IOBase
from collections import deque

# region fastio
BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

if sys.version_info[0] < 3:
    sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

file = sys.stdin
if os.environ.get('USER') == "loic":
    file = open("data.in")

line = lambda: file.readline().split()
ui = lambda: int(line()[0])
ti = lambda: map(int,line())
li = lambda: list(ti())

#######################################################################

def to_int_digits(n):
    return list(map(int, str(n)))

def solve():

    start = X
    mp = {start:0}

    q = deque()
    q.appendleft(start)

    while q:
        n = q.pop()
        if len(str(n)) == N:
            return mp[n]

        for d in set(to_int_digits(n)):
            ch = d * n
            if ch not in mp:
                q.appendleft(ch)
                mp[ch] = mp[n] + 1

    return str(-1)

for test in range(1,1+1):
    N,X = ti()

    print(solve())

file.close()

import sys
import os
from io import BytesIO, IOBase
from collections import deque

# region fastio
BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

if sys.version_info[0] < 3:
    sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

file = sys.stdin
if os.environ.get('USER') == "loic":
    file = open("data.in")

line = lambda: file.readline().split()
ui = lambda: int(line()[0])
ti = lambda: map(int,line())
li = lambda: list(ti())

#######################################################################

def to_int_digits(n):
    return list(map(int, str(n)))

def solve():

    start = X
    mp = {start:0}

    q = deque()
    q.appendleft(start)

    while q:
        n = q.pop()
        if len(str(n)) == N:
            return mp[n]

        for d in to_int_digits(n):
            ch = d * n
            if ch not in mp:
                q.appendleft(ch)
                mp[ch] = mp[n]+ 1

    return str(-1)

for test in range(1,1+1):
    N,X = ti()

    print(solve())

file.close()

from functools import lru_cache

num ,x = list(map(int,input().split()))

@lru_cache(maxsize=None)

def dp(nn_,xx_):

	y = str(xx_)
	if len(y)==nn_:
		return 0
	res = 1e9
	for ji in y:
		if int(ji)>1:
			res = min(res,1 + dp(nn_,xx_*int(ji)))
	return res

ans = dp(num,x)
if ans>=1e9:
	print(-1)
else:
	print(ans)

n, x = map(int, input().split())
ans = 100

def dfs(x, k=3, c=0):
    global ans
    if c + n - len(str(x)) >= ans:
        return -1
    if len(str(x)) >= n:
        return c
    j = 0
    for i in sorted(map(int, set(str(x))), reverse=True):
        if i <= 1:
            continue
        if j == k:
            break
        j += 1
        r = dfs(x * i, k, c + 1)
        if r == -1:
            continue
        assert r <= ans
        ans = r
    return ans

dfs(x, k=100)
print(ans if ans != 100 else -1)

from sys import stdin, stdout

n, x = [int(z) for z in stdin.readline().split()]
memo = {}

def f(x):
    if x in memo:
        return memo[x]

    x_s = str(x)
    if len(x_s) == n:
        memo[x] = 0
        return 0

    digits = set()
    for i in range(len(x_s)):
        if int(x_s[i]) > 1:
            digits.add(int(x_s[i]))

    if len(digits) == 0:
        memo[x] = 100
        return 100
    else:
        temp = 100
        for i in digits:
            temp = min(temp, 1+f(x*i))
        memo[x] = temp
        return temp

answer = f(x)
if answer >= 100:
    answer = -1

stdout.write(str(answer)+'\n')

# from heapq import heapify
# from itertools import count
# from multiprocessing.connection import answer_challenge
# import sys
# import os
# from math import ceil, floor, sqrt, gcd, factorial, log, log2
# from io import BytesIO, IOBase
# from collections import Counter
# # from itertools import permutations, combinations
# from bisect import bisect, insort, bisect_left
# # from functools import reduce
# from heapq import heapify, heappop, heappush

# # sys.setrecursionlimit(10**6)

# yes='YES'
# no='NO'
# Yes='Yes'
# No='No'

# inf=int(10e9) + 7
# BUFSIZE = 8192

# inp = lambda: int(input())
# mp = lambda: map(int, input().split())
# lst = lambda: list(map(int, input().split()))

# def sorter(arr, n):
#     c = 0
#     temp = arr.copy()
#     temp.sort()
#     ans=[]
#     for i in range(n):
#         if (arr[i] != temp[i]):
#             c+=1
#             u = i
#             v = arr.index(temp[i])
#             ans.append((u,v))
#             arr[u], arr[v] = arr[v], arr[u]
#     return ans

# def main():
#     for _ in range(inp()):
#         n=inp()
#         a=lst()
#         b=lst()
#         # ac = [(a[i], i) for i in range(n)]
#         # bc = [(b[i], i) for i in range(n)]
#         # ac.sort()
#         # bc.sort()
#         ta = a.copy()
#         tb = b.copy()

#         aa = a.copy()
#         bb = b.copy()

#         ans1 = sorter(aa, n)
#         ans2 = sorter(bb, n)

#         print(ans1, ans2)

#         # tb = b.copy()
#         for i, j in ans1:
#             tb[i], tb[j] = tb[j], tb[i]

#         # ta = a.copy()
#         for i, j in ans2:
#             ta[i], ta[j] = ta[j], ta[i]

#         if ta==sorted(a):
#             print('b', len(ans2))
#             for i, j in ans2:
#                 print(i, j)
#         elif tb==sorted(tb):
#             print('a', len(ans1))
#             for i, j in ans1:
#                 print(i, j)
#         else:
#             print(-1)

# class FastIO(IOBase):
#     newlines = 0

#     def __init__(self, file):
#         self._fd = file.fileno()
#         self.buffer = BytesIO()
#         self.writable = "x" in file.mode or "r" not in file.mode
#         self.write = self.buffer.write if self.writable else None

#     def read(self):
#         while True:
#             b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
#             if not b:
#                 break
#             ptr = self.buffer.tell()
#             self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
#         self.newlines = 0
#         return self.buffer.read()

#     def readline(self):
#         while self.newlines == 0:
#             b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
#             self.newlines = b.count(b"\n") + (not b)
#             ptr = self.buffer.tell()
#             self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
#         self.newlines -= 1
#         return self.buffer.readline()

#     def flush(self):
#         if self.writable:
#             os.write(self._fd, self.buffer.getvalue())
#             self.buffer.truncate(0), self.buffer.seek(0)

# class IOWrapper(IOBase):
#     def __init__(self, file):
#         self.buffer = FastIO(file)
#         self.flush = self.buffer.flush
#         self.writable = self.buffer.writable
#         self.write = lambda s: self.buffer.write(s.encode("ascii"))
#         self.read = lambda: self.buffer.read().decode("ascii")
#         self.readline = lambda: self.buffer.readline().decode("ascii")

# sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
# input = lambda: sys.stdin.readline().rstrip("\r\n")

# if __name__ == "__main__":
#     main()

from heapq import heapify
from itertools import count
from multiprocessing.connection import answer_challenge
import sys
import os
from math import ceil, floor, sqrt, gcd, factorial, log, log2
from io import BytesIO, IOBase
from collections import Counter
# from itertools import permutations, combinations
from bisect import bisect, insort, bisect_left
# from functools import reduce
from heapq import heapify, heappop, heappush

# sys.setrecursionlimit(10**6)

yes='YES'
no='NO'
Yes='Yes'
No='No'

inf=int(10e9) + 7
BUFSIZE = 8192

inp = lambda: int(input())
mp = lambda: map(int, input().split())
lst = lambda: list(map(int, input().split()))

def lenn(x):
    return len(str(x))

bigdic = dict()

def func(x):
    dig = list(set([int(i) for i in str(x) if i!='0' and i!='1']))
    t = []
    for i in dig:
        if i*x not in bigdic:
            t.append(i*x)
            bigdic[i*x] = 0

    return t

def main():
    n,x = mp()

    if max([int(i) for i in str(x)])<=1:
        print(-1)
    else:
        bigdic[x] = 0
        old = [x]
        flag = False
        c = 0
        while not flag:
            new = []
            for i in sorted(old):
                if lenn(i)==n:
                    flag = True
                    break
                else:
                    new+=func(i)
            if flag:
                break
            else:
                c+=1
                old = new.copy()

        print(c)

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

if __name__ == "__main__":
    main()

n, x = input().split()
n = int(n)
ans = float('inf')

visited = set()
queue = [(x, 0),]

while queue:
    val, step = queue.pop(0)
    if val not in visited:
        visited.add(val)
        if len(val) == n:
            ans = step
            break

        elif len(val) < n:
            pos = set(list(val))
            for num in pos:
                if num != '0':
                    new = str(int(val)*int(num))
                    queue.append((new, step + 1))

if ans == float('inf'):
    print(-1)
else:
    print(ans)

n, x = input().split()
n = int(n)
ans = float('inf')

visited = set()
queue = [(x, 0),]

while queue:
    val, step = queue.pop(0)
    if val not in visited:
        visited.add(val)
        if len(val) == n:
            ans = min(ans, step)

        elif len(val) < n:
            pos = set(list(val))
            for num in pos:
                if num != '0':
                    new = str(int(val)*int(num))
                    queue.append((new, step + 1))

if ans == float('inf'):
    print(-1)
else:
    print(ans)

import collections
n,k = [int(x) for x in input().split()]
q = collections.deque([k])
d = {k:0}
ans = -1
while(len(q) > 0):
    k = q.pop()
    s = str(k)
    if(len(s) == n):
        ans = d[k]
        break

    for x in s:
        if(x == "0"):
            continue
        w = k*int(x)
        if(w not in d):
            d[w] = d[k] + 1
            q.appendleft(w)
print(ans)

# import sys
# sys.stdin = open('in.txt', 'r')
# sys.stdout = open('out.txt', 'w')

n,x = [int(x) for x in input().split()]
dp = {}
def solve(s):
    if(len(s) == n):
        return 0

    val = int(s)

    if(val in dp):
        return dp[val]

    N = len(s)
    ans = 10**15;
    for i in range(0, N):
        if(s[i] == '0' or s[i] == '1'):
            continue
        temp = str(val*int(s[i]));
        ans = min(ans, 1+solve(temp));

    dp[val] = ans
    return dp[val];
x = str(x)
ans = solve(x)
if ans >= 10**15:
    ans = -1
print(ans)

import queue
def solve():
    n, st = map(int, input().split())
    qu = queue.Queue()
    if len(str(st)) < n:
        qu.put((st, 0))
    elif len(str(st)) == n:
        print(0)
        return
    else:
        print(-1)
        return
    vis = set()
    happyEnd = False
    ans = -1

    while qu.qsize():
        x, cnt = qu.get()
        if x in vis:continue
        vis.add(x)
        df = x
        a = set(map(int,list(str(x))))
        for digit in a:
            if digit<=1:continue
            nxt = df *digit;
            if nxt in vis:
                continue
            nLen = len(str(nxt))
            if nLen == n:
                if not happyEnd:
                    happyEnd = True
                    ans = cnt + 1
                else:
                    ans = min(ans, cnt+1)
            elif nLen > n:
                continue
            qu.put((nxt, cnt+1))

    if happyEnd:
        print( ans)
    else:
        print(-1)
solve()

import queue
def solve():
    n, st = map(int, input().split())
    qu = queue.Queue()
    if len(str(st)) < n:
        qu.put((st, 0))
    elif len(str(st)) == n:
        print(0)
        return
    else:
        print(-1)
        return
    vis = set()
    happyEnd = False
    ans = -1

    while qu.qsize():
        x, cnt = qu.get()
        if x in vis:continue
        vis.add(x)
        df = x
        a = set(map(int,list(str(x))))
        for digit in a:
            if digit<=1:continue
            nxt = df *digit;
            if nxt in vis:
                continue
            nLen = len(str(nxt))
            if nLen == n:
                if not happyEnd:
                    happyEnd = True
                    ans = cnt + 1
                else:
                    ans = min(ans, cnt+1)
            elif nLen > n:
                continue
            qu.put((nxt, cnt+1))

    if happyEnd:
        print(ans)
    else:
        print(-1)
solve()

from functools import lru_cache
from time import sleep

INF = 1e100
s = dict()
# @lru_cache(None)
def solve(x, cur, k):
    if x in s:
        return s[x] + cur
    if len(str(x)) == k:
        return cur
    if len(str(x)) > k:
        return INF
    if x == 0 and k != 1:
        return INF
    ans = INF
    for i in str(x):
        if i != '1':
            ans = min(ans, solve(int(i) * x, cur + 1, k))
    s[x] = ans - cur
    return ans

k, x = map(int, input().split())
x = solve(x, 0, k)
if x < INF:
    print(x)
else:
    print(-1)

from asyncio import QueueEmpty
from collections import deque

n, x = map(int, input().split())
que = deque()
tup = (x, 0)
que.append(tup)
visited = {x}
result = -1
LIMIT = 10**n-1
count = 0
while que:
    num, step = que.popleft()
    List = list(map(int, str(num)))
    if len(List) >= n:
        result = step
        break
    Set = set(List)
    if 0 in Set:
        Set.remove(0)
    if 1 in Set:
        Set.remove(1)
    for i in Set:
        add_q = num * i
        if add_q < LIMIT and (add_q not in visited):
            visited.add(add_q)
            que.append((add_q, step+1))
    count += 1
print(result)

# check_ones = list(map(lambda x: x == 1, List))
# checker = True
# for i in check_ones:
#     if not i:
#         checker = False
#         break
# if checker:
#     if len(check_ones) < n:
#         print("-1")
#     else:
#         print("0")
# else:
#     count = 0
#     List = list(map(int, str(x)))
#     while len(List) < n:
#         x *= max(List)
#         count += 1
#         List = list(map(int, str(x)))
#         print(count, x, len(List))
#         # if len(List) < n and 0 in List:
#         #     count += (n - len(List))
#         #     break
#     print(count)

def f(x, n, k, dt, cnt, st):
    if len(str(x)) == n:
        return 0
    mn = 1000
    cnt += 1
    for elem in str(x):
        if elem not in st:
            a = int(elem) * x
            if a not in k:
                b = f(a, n, k, dt, cnt, st)
                mn = min(mn, b)
                k.add(a)
                dt[a] = [cnt, b]
            else:
                dt[a][0] = min(cnt, dt[a][0])
                mn = min(mn, dt[a][1])
    return mn + 1

n, x = list(map(int, input().split()))
ans = f(x, n, set(), {}, 0, set(['1', '0']))
if ans >= 1000:
    print(-1)
else:
    print(ans)

# ----------------------------IMPORTING LIBRARIES----------------------------#
import math
import itertools
import heapq
from math import floor, ceil
from collections import deque
import sys
from collections import Counter

# ----------------------------LAMBDAS AND DEFAULT----------------------------#
I = lambda: list(map(int, input().split()))
M = lambda: map(int, input().split())
input = sys.stdin.readline
#sys.setrecursionlimit(10000)
MOD = 10 ** 9 + 7

# -----------------------------STANDARD FUNCTIONS----------------------------#
def lcm(a, b):
    return abs(a * b) // math.gcd(a, b)

def gcd(a, b):
    if b == 0:
        return a
    return gcd(b, a % b)

def solve(total):
    ans = []
    m4, m6 = total // 4, total // 6
    for i in range(0, m4 + 1):
        for j in range(0, m6 + 1):
            if 4 * i + 6 * j == total:
                ans.append(i + j)
    return ans

def isSubsequence(s, t):
    for i in range(0, len(s)):
        try:
            index = t.index(s[i])
        except ValueError:
            return False
        t = t[index + 1:]
    return True

def bisect_right(a, x):
    lo, hi = 0, len(a)
    while lo < hi:
        mid = lo + (hi - lo) // 2
        if a[mid] > x:
            hi = mid
        else:
            lo = mid + 1
    return lo

def bisect_left(a, x):
    lo, hi = 0, len(a)
    while lo < hi:
        mid = lo + (hi - lo) // 2
        if a[mid] < x:
            lo = mid + 1
        else:
            hi = mid
    return lo

def binary_search(nums, target):
    left, right = 0, len(nums) - 1
    while left <= right:
        pivot = left + (right - left) // 2
        if nums[pivot] == target:
            return pivot
        if target < nums[pivot]:
            right = pivot - 1
        else:
            left = pivot + 1
    return -1

def modexp(x, n):
	if (n == 0) :
		return 1
	elif (n % 2 == 0) :
		return modexp((x * x) % m, n // 2)
	else :
		return (x * modexp((x * x) % m,
						(n - 1) / 2) % m)

def primeModulo(a, b):
	c = gcd(a, b)
	a = a // c
	b = b // c
	d = modexp(b, m - 2)
	ans = ((a % m) * (d % m)) % m
	return ans

# ------------------------------HELPER FUNCTION------------------------------#
def fun():
    return

# sys.stdout.write(str(X) + "\n")

def solve(_):
    N, X = I()
    glob = []
    soFar = set()
    ans = float('inf')
    mem = {}
    def recursion(num, mul, a):
        poss = []
        for i in str(num):
            poss.append(int(i))
        if num in soFar:
            return mem[num]
        soFar.add(num)
        if len(str(num)) == N:
            mem[num] = mul
            return mul

        for i in poss:
            nex = num*i
            if nex == num or nex == 0:
                pass
            else:
                a = min(recursion(num*i, mul, a)+1, a)
        mem[num] = a
        return a

    ans = recursion(X, 0, float('inf'))

    if ans == float('inf'):
        print(-1)
    else:
        print(ans)
# ---------------------------------DRIVER CODE--------------------------------#
TC = 1
#TC = int(input())
for testcases in range(TC):
    solve(testcases)

import sys
from math import inf
from collections import deque
input = sys.stdin.readline

n,x = map(int,input().split())

vis = set()
ans = 0
q = deque([x])

if len(str(x)) == n:
    print(0)
elif len(str(x)) > n:
    print(-1)
else:
    flag = True
    while q:
        ans += 1
        for i in range(len(q)):
            now = q.popleft()

            for j in range(2,10):
                if str(j) in str(now):
                    nxt = now * j
                    if len(str(nxt)) == n:
                        flag = False

                    if nxt not in vis:
                        q.append(nxt)
                        vis.add(nxt)

        if len(q) == 0:
            ans = -1
        if not flag:
            break

    print(ans)

from collections import defaultdict
N, X = map(int,input().split())
original = X
d = defaultdict(int)
def calc(s, dd):
    X = s
    if dd[X] > 0:
        return dd[X]
    digits = []
    digitsnum = 0
    while X > 0:
        digitsnum += 1
        if X % 10 not in digits:
            digits.append(X%10)
        X //= 10
    if digitsnum == N:
        dd[s] = 0
        return 0
    if digitsnum > N:
        return 10**30
    else:
        mn = 10**30
        for d in digits:
            if d != 1 and d != 0:
                X = s*d
                mn = min(mn, calc(X,dd) + 1)
        dd[s] = mn
        return mn
ans = calc(X,d)
if ans >= 10**30:
    print(-1)
else:
    print(ans)

N, X = map(int, input().split())

INF = 10**18

D = {X: 0}
Q = [X]

for i in Q:
    d = D[i]
    s = str(i)
    n = len(s)
    if n == N:
        print(d)
        break
    elif n > N:
        continue

    for c in s:
        j = i * (ord(c) - ord('0'))
        if d + 1 < D.get(j, INF):
            D[j] = d+1
            Q.append(j)
else:
    print(-1)

l = list(map(int, input().split()))
n = l[0]
x = l[1]
q = [x]
times = 0
opre = {}
opre[x] = 0
result=-1
while len(q) > 0:
    x = q.pop(0)
    str_x = str(x)
    if len(str_x) == n:
        result = opre[x]
        break
    for digit in str_x:
        new_number = int(digit) * x
        if new_number not in opre:
            q.append(new_number)
            opre[new_number] = opre[x] + 1
print(result)

import os,sys
from io import BytesIO, IOBase

from collections import defaultdict,deque,Counter
from bisect import bisect_left,bisect_right
from heapq import heappush,heappop
from functools import lru_cache
from itertools import accumulate
import math

# Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
    newlines = 0
    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None
    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()
    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()
    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

# for _ in range(int(input())):
#     n = int(input())
#     a = list(map(int, input().split(' ')))

# for _ in range(int(input())):
#     n = int(input())
#     a = list(map(int, input().split(' ')))
#     m = int(input())
#     b = list(map(int, input().split(' ')))
#     ma = max(a)
#     mb = max(b)
#     if ma < mb:
#         print('Bob')
#         print('Bob')
#     elif ma > mb:
#         print('Alice')
#         print('Alice')
#     else:
#         print('Alice')
#         print('Bob')

# for _ in range(int(input())):
#     n = int(input())
#     a = list(map(int, input().split(' ')))
#     m = int(input())
#     b = list(map(int, input().split(' ')))
#     idx = sum(b) % n
#     print(a[idx])

# for _ in range(int(input())):
#     n = int(input())
#     a = list(map(int, input().split(' ')))
#     b = list(map(int, input().split(' ')))
#     ans = []
#     for i in range(n):
#         ma = min(a[i:])
#         for j in range(i, n):
#             if a[j] == ma:
#                 idx = j
#                 break
#         if idx != i:
#             a[idx], a[i] = a[i], a[idx]
#             b[idx], b[i] = b[i], b[idx]
#             ans.append((i, idx))

#     i = 0
#     j = 0
#     while i <= j < n:
#         while j < n and a[j] == a[i]:
#             j += 1
#         for k in range(i, j):
#             mb = min(b[k: j])
#             for l in range(k, j):
#                 if b[l] == mb:
#                     idx = l
#                     break
#             if idx != k:
#                 b[idx], b[k] = b[k], b[idx]
#                 ans.append((k, idx))
#         i = j

#     if b != sorted(b):
#         print(-1)
#     else:
#         print(len(ans))
#         for i, j in ans:
#             print(i + 1, j + 1)
#
n, x = list(map(int, input().split(' ')))
t = 10 ** (n - 1)
if x == 1:
    print(-1)
else:
    q = deque()
    q.append((x, 0))
    vis = set([x])
    ok = False
    k = 0
    while q:
        k += 1
        x, dis = q.popleft()
        s = str(x)
        if x >= t:
            print(dis)
            ok = True
            break
        st = set()
        for i in range(len(s)):
            if s[i] != '0' and s[i] != '1':
                st.add(int(s[i]))
        for i in st:
            if x * i not in vis:
                q.append((x * i, dis + 1))
                vis.add(x * i)
    if not ok:
        print(-1)

vis = dict()

def try_digits(n, x):
    if len(str(x)) == n:
        return 0

    digits = set()
    ans = 1000
    for digit in str(x):
        if digit == '0' or digit == '1':
            continue
        if digit not in digits:
            digits.add(int(digit))
            prod = int(digit) * x
            if prod not in vis:
                vis[prod] = try_digits(n, prod) + 1
            ans = min(ans, vis[prod])
    return ans

def solve():
    line = input().split()
    # print(line)
    n = int(line[0])
    x = int(line[1])
    ans = try_digits(n, x)
    print(-1) if ans == 1000 else print(ans)

# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    t = 1
    # t = int(input())
    while t > 0:
        solve();
        t -= 1

class Solution:
    def dfs(self, n, x):
        # print(x)
        if x in self.memo:
            return self.memo[x]

        if len(str(x)) == n:
            return 0

        if len(str(x)) > n:
            return 10000000

        min_step_required = 10000000
        # print(list(str(x)))
        for d in map(int, list(str(x))):
            if d == 1 or d == 0: continue
            min_step_required = min(min_step_required, 1+ self.dfs(n, d*x))

        self.memo[x] = min_step_required
        return min_step_required

    def solve(self, n, x):
        self.memo = {}
        res = self.dfs(n, x)
        print(res if res != 10000000 else -1)

def main():
    n, x = map(int, input().split())
    S = Solution()

    S.solve(n, x)

if __name__ == "__main__":
    main()

import sys

def play_card_Afirst(A,B):
    if max(A)>=max(B):
        return 'Alice'
    else:
        return 'Bob'
def play_card_Bfirst(A,B):
    if max(B)>= max(A):
        return 'Bob'
    return 'Alice'

def shuffle(va, n, vb):
    return va[sum(vb)%n]

def double_sort(A,B,n):
    tAB = list(zip(A,B))
#     print(tAB)
    sort_rank = sorted(enumerate(tAB), key=lambda x:x[1])
    for (_,x),(_,y) in zip(sort_rank[:-1],sort_rank[1:]):
#         print(x,y)
        if (x[0]-y[0])*(x[1]-y[1])<0:
            print(-1)
            return
    l = [x[1][0] for x in sort_rank]
    assert(all(l[i] <= l[i+1] for i in range(len(l) - 1)))
    l = [x[1][1] for x in sort_rank]
    assert(all(l[i] <= l[i+1] for i in range(len(l) - 1)))
    swaps = []
    now_loc = list(range(n))
    now_value = list(range(n))
    for i,(after,_) in enumerate(sort_rank):
        LocJ = now_loc[after]
        if LocJ!=i:
            valueI = now_value[i]
            swaps.append((LocJ,i))
            now_loc[after] = i
            now_loc[valueI] = LocJ
            now_value[i] = after
            now_value[LocJ] = valueI
    print(len(swaps))
    for x,y in swaps:
        print(x+1,y+1)
cache = {}
def RL(x,n):
    if x in cache.keys():
        return cache[x]
    digits = list(str(x))
    if len(digits)>n:
        return float('inf')
    minD = int(min([k for k in digits if k != '0']))
    maxD = int(max(digits))
    if len(digits) == n :
        return 0
    if maxD == 1:
        return float('inf')
    cache[x] = 1+min([RL(x*b,n) for b in [int(k) for k in digits if k not in '01']])
    return cache[x]

n,x = [int(x) for x in sys.stdin.readline().split()]
result = RL(x,n)
if result == float('inf'):
    print(-1)
else:
    print (result)
'''
r = int(sys.stdin.readline())
for j in range(r):
    n = int(sys.stdin.readline())
    A = [int(x) for x in sys.stdin.readline().split()]
    B = [int(x) for x in sys.stdin.readline().split()]
    print(double_sort(A,B,n))'''

def is_sorted(arr,r=False):
    n=len(arr)
    if not r :
        for i in range(1,n):
            if arr[i]<arr[i-1] :
                return False
        return True
    else:
        for i in range(1,n):
            if arr[i]>arr[i-1] :
                return False
        return True

def freq(arr) :
    d={}
    for i in arr :
        d[i]=d.get(i,0)+1
    return d

def fac(n):
    p=1
    for i in range(1,n+1):
        p*=i
    return p

from functools import lru_cache

@lru_cache(maxsize=None)
def solve(m,n) :

    if len(str(m))>=n :
        return 0

    r=[]
    k=m
    while k>0 :
        r.append(k%10)
        k=k//10

    if r and max(r)==1 :
        return -1

    try:
        while True:
            r.remove(1)
    except ValueError:
        pass
    mn=100000000000000000

    for i in r :
        x=solve(m*i,n)

        if x>=0 :
            mn=min(mn,x)

    return 1+mn

#from bisect import bisect_left as bisect
from math import ceil,floor
from sys import stdin #setrecursionlimit
input = stdin.buffer.readline
#setrecursionlimit(400000)

n,m= list(map(int, input().split()))
print(solve(m,n))

'''

for _ in range(int(input())) :
    n=int(input())
    print(solve())

n=int(input())

x=input().strip().decode("utf-8")

n,m= list(map(int, input().split()))

n=int(input())
    arr=list(map(int, input().split()))

n,k= list(map(int, input().split()))
arr=list(map(int, input().split()))

arr=list(map(int, input().strip().decode("utf-8")))

n,m= [int(x) for x in input().split()]
arr=[list(map(int, input().split())) for _ in range(n)]

n,m= [int(x) for x in input().split()]
arr=[list(map(int, input().strip().decode("utf-8"))) for _ in range(n)]

n=int(input())
arr=[list(map(int, input().split())) for _ in range(n)]

n,m= list(map(int, input().split()))
    arr=[list(input().strip().decode("utf-8")) for _ in range(n)]

for _ in range(int(input())) :

    n=int(input())
    arr=list(map(int, input().split()))

    d={}
    leaves={}

    for i in range(n):
        d[i+1]=[]
        leaves[i+1]=1

    for i in range(1,n):
        d[arr[i-1]].append(i+1)
        if arr[i-1] in leaves :
            leaves.pop(arr[i-1])

'''

from math import gcd, sqrt, log, factorial
from functools import cmp_to_key
from string import ascii_lowercase as alph
import os, sys
from itertools import permutations, combinations
import heapq
from io import BytesIO, IOBase
from collections import deque, Counter

############################################################################
#								FAST-IO								       #
#								TEMPLATES                                  #
############################################################################

fast = True
if fast:

	BUFSIZE = 8192

	class FastIO(IOBase):
		newlines = 0

		def __init__(self, file):
			self._fd = file.fileno()
			self.buffer = BytesIO()
			self.writable = "x" in file.mode or "r" not in file.mode
			self.write = self.buffer.write if self.writable else None

		def read(self):
			while True:
				b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
				if not b:
					break
				ptr = self.buffer.tell()
				self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
			self.newlines = 0
			return self.buffer.read()

		def readline(self):
			while self.newlines == 0:
				b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
				self.newlines = b.count(b"\n") + (not b)
				ptr = self.buffer.tell()
				self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
			self.newlines -= 1
			return self.buffer.readline()

		def flush(self):
			if self.writable:
				os.write(self._fd, self.buffer.getvalue())
				self.buffer.truncate(0), self.buffer.seek(0)

	class IOWrapper(IOBase):
		def __init__(self, file):
			self.buffer = FastIO(file)
			self.flush = self.buffer.flush
			self.writable = self.buffer.writable
			self.write = lambda s: self.buffer.write(s.encode("ascii"))
			self.read = lambda: self.buffer.read().decode("ascii")
			self.readline = lambda: self.buffer.readline().decode("ascii")

	def print(*args, **kwargs):
		"""Prints the values to a stream, or to sys.stdout by default."""
		sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
		at_start = True
		for x in args:
			if not at_start:
				file.write(sep)
			file.write(str(x))
			at_start = False
		file.write(kwargs.pop("end", "\n"))
		if kwargs.pop("flush", False):
			file.flush()

	if sys.version_info[0] < 3:
		sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
	else:
		sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

	input = lambda: sys.stdin.readline().rstrip("\r\n")

if os.path.exists('input.txt'):
	sys.stdin = open('input.txt')
	sys.stdout = open('output.txt', 'w')

INF = float('inf')

def C(n, k, mod):
	cntn = 0
	cntk = 0
	if 0 <= k <= n:
		nn = 1
		kk = 1
		for t in range(1, min(k, n - k) + 1):
			nn *= n
			cntn = (cntn * mod + nn) // mod
			nn %= mod
			kk *= t
			cntk = (cntk * mod + kk) // mod
			kk %= mod
			n -= 1
		return (nn + cntn * mod) // (kk + cntk * mod) % mod
	else:
		return 0

def isPrime(n):
	if n == 1: return 0
	if n % 2 == 0: return n == 2
	i = 3
	while i * i <= n:
		if n % i == 0:
			return 0
		i += 2
	return 1

def divCeil(a, b):
	return (a - 1) // b + 1

def readList():
	return [int(i) for i in input().split()]

def getSum(prefSum, l, r):
	if l == 0:
		return prefSum[r]
	return prefSum[r] - prefSum[l - 1]

def getProd(l, r):
	global prefProd
	if l == 0:
		return prefProd[r]
	return prefProd[r] // prefProd[l - 1]

def getsum(BITTree,i):
	s = 0
	i = i + 1
	while i > 0:
		s += max(1, BITTree[i])
		i -= i & (-i)
	return s

def updatebit(BITTree , n , i ,v):
	i += 1
	while i <= n:
		BITTree[i] += v
		i += i & (-i)

def construct(arr, n):
	BITTree = [0] * (n + 1)

	for i in range(n):
		updatebit(BITTree, n, i, arr[i])

	return BITTree

def solve():
	n, x = readList()
	proc = [x]
	ans = INF
	wave = 0
	while True:
		new_proc = set()
		for x in proc:
			if len(str(x)) >= n:
				ans = min(ans, wave)
				continue
			for i in range(2, 10):
				if str(i) in str(x):
					new_proc.add(i * x)
		if len(new_proc) == 0:
			break
		proc = list(new_proc)
		wave += 1
	if ans == INF:
		print(-1)
	else:
		print(ans)

t = 1
while t:
	t -= 1
	solve()

from queue import Queue as Q
n, x = map(int, input().split())
q = Q()
q.put((x, 0))
was = set()
while not q.empty():
    r = q.get()
    if r[0] >= 10**(n-1):
        print(r[1])
        break
    else:
        for i in str(r[0]):
            if i not in [0, 1]:
                new = int(i)*r[0]
                if new not in was:
                    was.add(new)
                    q.put((new, r[1]+1))
else:
    print(-1)

import os,sys
from io import BytesIO, IOBase

from collections import defaultdict,deque,Counter
from bisect import bisect_left,bisect_right
from heapq import heappush,heappop
from functools import lru_cache
from itertools import accumulate
import math

# Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
    newlines = 0
    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None
    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()
    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()
    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

# for _ in range(int(input())):
#     n = int(input())
#     a = list(map(int, input().split(' ')))

# for _ in range(int(input())):
#     n = int(input())
#     a = list(map(int, input().split(' ')))
#     m = int(input())
#     b = list(map(int, input().split(' ')))
#     ma = max(a)
#     mb = max(b)
#     if ma < mb:
#         print('Bob')
#         print('Bob')
#     elif ma > mb:
#         print('Alice')
#         print('Alice')
#     else:
#         print('Alice')
#         print('Bob')

# for _ in range(int(input())):
#     n = int(input())
#     a = list(map(int, input().split(' ')))
#     m = int(input())
#     b = list(map(int, input().split(' ')))
#     idx = sum(b) % n
#     print(a[idx])

# for _ in range(int(input())):
#     n = int(input())
#     a = list(map(int, input().split(' ')))
#     b = list(map(int, input().split(' ')))
#     ans = []
#     for i in range(n):
#         ma = min(a[i:])
#         for j in range(i, n):
#             if a[j] == ma:
#                 idx = j
#                 break
#         if idx != i:
#             a[idx], a[i] = a[i], a[idx]
#             b[idx], b[i] = b[i], b[idx]
#             ans.append((i, idx))

#     i = 0
#     j = 0
#     while i <= j < n:
#         while j < n and a[j] == a[i]:
#             j += 1
#         for k in range(i, j):
#             mb = min(b[k: j])
#             for l in range(k, j):
#                 if b[l] == mb:
#                     idx = l
#                     break
#             if idx != k:
#                 b[idx], b[k] = b[k], b[idx]
#                 ans.append((k, idx))
#         i = j

#     if b != sorted(b):
#         print(-1)
#     else:
#         print(len(ans))
#         for i, j in ans:
#             print(i + 1, j + 1)

n, x = list(map(int, input().split(' ')))
t = 10 ** (n - 1)
if x == 1:
    print(-1)
else:
    q = deque()
    q.append((x, 0))
    vis = set([x])
    ok = False
    k = 0
    while q:
        k += 1
        x, dis = q.popleft()
        s = str(x)
        if x >= t:
            print(dis)
            ok = True
            break
        st = set()
        for i in range(len(s)):
            if s[i] != '0' and s[i] != '1':
                st.add(int(s[i]))
        for i in st:
            if x * i not in vis:
                q.append((x * i, dis + 1))
                vis.add(x * i)
    if not ok:
        print(-1)

import io,os
from collections import deque

input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def main(t):

    n,x = map(int,input().split())
    dic = {}
    queue = deque()
    queue.append([str(x),0])

    while queue:
        s,step = queue.popleft()
        for c in s:
            nexts = str(int(s)*int(c))
            if len(nexts)==n:
                print(step+1)
                return
            if nexts in dic:  continue
            dic[nexts] = 1
            queue.append([nexts,step+1])

    print(-1)

T = 1 #int(input())
t = 1
while t<=T:
    main(t)
    t += 1

n, x = map(int, input().split())
if not any([str(i) in str(x) for i in range(2, 10)]):
    print(-1)
    exit()
dp = [set() for i in range(n * 10)]
dp[0].add(x)
for j in range(n * 10 - 1):
    for k in dp[j]:
        for i in range(2, 10):
            if str(i) in str(k):
                dp[j + 1].add(k * i)
                if len(str(k * i)) == n:
                    print(j + 1)
                    exit()

import io,os
from collections import deque

input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def main(t):

    n,x = map(int,input().split())

    queue = deque()
    queue.append([str(x),0])
    dic = {}

    while queue:
        s,step = queue.popleft()
        for c in s:
            nexts = str(int(s)*int(c))
            if len(nexts)==n:
                print(step+1)
                return
            if nexts in dic:  continue
            dic[nexts] = 1
            queue.append([nexts,step+1])

    print(-1)

T = 1 #int(input())
t = 1
while t<=T:
    main(t)
    t += 1

from collections import deque
from itertools import count
from sys import stdin, stderr

n, x = [int(x) for x in stdin.read().split()]

target_lo = 10 ** (n - 1)

seen = {x}
queue = deque([(x, 0)])
while queue:
    x, n_iters = queue.popleft()
    v = x
    while v:
        v, mod = divmod(v, 10)
        t = x * mod
        if t in seen:
            continue
        if t >= target_lo:
            print(n_iters + 1)
            exit()
        else:
            seen.add(t)
            queue.append((t, n_iters + 1))
print(-1)

import sys
import math
import heapq
import bisect
from collections import Counter, defaultdict, deque
from io import BytesIO, IOBase
from types import GeneratorType
import string

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        import os
        self.os = os
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None
        self.BUFSIZE = 8192

    def read(self):
        while True:
            b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, self.BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, self.BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            self.os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

def get_int():
    return int(input())

def get_ints():
    return list(map(int, input().split(' ')))

def get_int_grid(n):
    return [get_ints() for _ in range(n)]

def get_str():
    return input().strip()

def get_strs():
    return get_str().split(' ')

def yes_no(b):
    if b:
        return "YES"
    else:
        return "NO"

def bootstrap(f, stack=[]):
    def wrappedfunc(*args, **kwargs):
        if stack:
            return f(*args, **kwargs)
        else:
            to = f(*args, **kwargs)
            while True:
                if type(to) is GeneratorType:
                    stack.append(to)
                    to = next(to)
                else:
                    stack.pop()
                    if not stack:
                        break
                    to = stack[-1].send(to)
            return to

    return wrappedfunc

def binary_search(good, left, right, delta=1, right_true=False):
    limits = [left, right]
    while limits[1] - limits[0] > delta:
        if delta == 1:
            mid = sum(limits) // 2
        else:
            mid = sum(limits) / 2
        if good(mid):
            limits[int(right_true)] = mid
        else:
            limits[int(~right_true)] = mid
    if good(limits[int(right_true)]):
        return limits[int(right_true)]
    else:
        return False

def prefix_sums(a):
    p = [0]
    for x in a:
        p.append(p[-1] + x)
    return p

def solve_a():
    n = get_int()
    a = get_ints()
    m = get_int()
    b = get_ints()
    m = max(a)
    M = max(b)
    if m > M:
        print("Alice")
        print("Alice")
    elif M > m:
        print("Bob")
        print("Bob")
    else:
        print("Alice")
        print("Bob")
    return

def solve_b():
    n = get_int()
    a = get_ints()
    m = get_int()
    b = get_ints()

    S = sum(b)
    i = S % n
    return a[i]

def solve_c():
    n = get_int()
    a = get_ints()
    b = get_ints()

    c = [(a[i], b[i], i) for i in range(n)]
    c.sort()

    for i in range(1, n):
        if c[i][1] < c[i - 1][1]:
            print(-1)
            return

    pos = [None] * n
    for i in range(n):
        pos[c[i][-1]] = i

    swaps = pos
    ans = []
    for i in range(n):
        for j in range(i + 1, n):
            if swaps[i] > swaps[j]:
                ans.append((i + 1, j + 1))
                swaps[i], swaps[j] = swaps[j], swaps[i]

    print(len(ans))
    for line in ans:
        print(*line)
    return

def solve_d():
    n, x = get_ints()
    if x == 1:
        if n == 1:
            return 0
        else:
            return -1
    dp = {}
    q = deque([(x, 0)])
    small = 10 ** (n - 1)
    big = small * 10

    while q:
        y, c = q.popleft()
        if y in dp:
            continue
        else:
            dp[y] = c
        for x in str(y):
            z = int(x)
            p = z * y
            if p in dp or p >= big:
                continue
            else:
                q.append((p, c + 1))
                if p >= small:
                    return c + 1
    return -1

print(solve_d())

from functools import lru_cache
n, x = map(int, input().split())
@lru_cache(None)
def F(x):
	if len(str(x)) >= n:
		return 0
	z = 100
	for i in range(2, 10):
		if str(i) in str(x):
			z = min(z, F(x * i) + 1)
	return z
z = F(x)
if z == 100:
	z = -1
print(z)

inf = float("inf")

def get_next_state(mult: int, state: list):
    new_state = list(state)
    for idx, fac in enumerate((2,3,5,7)):
        while mult%fac == 0:
            new_state[idx] += 1
            mult //= fac
    return tuple(new_state)

# dp[(2s, 3s, 5s, 7s)]
def dumb(n, x, state: tuple, dp: dict):
    if len(str(x)) == n:
        return 0
    if state in dp:
        return dp[state]

    ans = inf
    for i in range(2,10):
        if str(i) in str(x):
            next_state = get_next_state(i, state)
            ans = min(ans, 1+dumb(n, x*i, next_state, dp))

    dp[state] = ans
    return ans

n, x = [int(x) for x in input().split()]
ans = dumb(n, x, (0,0,0,0), {})
print(-1 if ans == inf else ans)

# Problem: D. Required Length
# Contest: Codeforces - Educational Codeforces Round 129 (Rated for Div. 2)
# URL: https://codeforces.com/problemset/problem/1681/D
# Memory Limit: 512 MB
# Time Limit: 2000 ms
#
# Powered by CP Editor (https://cpeditor.org)
from collections import *
for _ in range(1):
	n,m=map(int,input().split())
	z=deque([[m,0]])
	vis=Counter([])
	ans=-1
	while(z):
		x=z.popleft()
		a=str(x[0])
		if(len(a)==n):
			ans=x[1]
			break
		for j in range(len(a)):
			p=int(a[j])*int(a)
			if(vis[p]==0):
				z.append([p,x[1]+1])
				vis[p]=1
	print(ans)

from functools import lru_cache
def minops(x):

    @lru_cache(None)
    def solve(x):
        if x>=10**(n-1):
            return 0
        numset=set(str(x))

        res=float('inf')
        for i in numset:
            i=int(i)
            if i in [0,1]:
                continue
            res=min(res,solve(x*i)+1)

        return res

    ans=solve(x)
    return  ans if ans!=float('inf')  else -1

n,x=[int(x) for x in input().split()]
check=True
ans=0
print(minops(x))

import sys
input = sys.stdin.readline
n,x=map(int,input().split())
from collections import defaultdict,deque
ten=[1]
for i in range(20):
  ten.append(ten[-1]*10)
if ten[n-1]<=x<ten[n]:
  print(0)
  exit()
if x>=ten[n]:
  print(-1)
  exit()
dist = defaultdict(int)
que = deque([x])
dist[x] = 0
while que:
  v = que.popleft()
  e = dist[v]
  for i in range(2,10):
    vv=str(v)
    if str(i) in vv:
      nxt=v*i
      if nxt>=ten[n]:
        continue
      if nxt not in dist:
        dist[nxt]=e+1
        que.append(nxt)
      if ten[n-1]<=nxt<ten[n]:
        print(dist[nxt])
        exit()
print(-1)

from functools import lru_cache
n,x = list(map(int,input().split()))
@lru_cache(maxsize=None)
def dp(nn,xx):
	y = str(xx)
	if len(y)==nn:
		return 0
	res = 1e9
	for j in y:
		if int(j)>1:
			res = min(res,1 + dp(nn,xx*int(j)))
	return res
res = dp(n,x)
if res>=1e9:
	print(-1)
else:
	print(res)

def I(): return input().strip()
def II(): return int(input().strip())
def LI(): return [*map(int, input().strip().split())]
import sys, os, copy, string, math, time, functools, fractions
from io import BytesIO, IOBase
from heapq import heappush, heappop, heapify
from bisect import bisect_left, bisect_right
from collections import deque, defaultdict, Counter, OrderedDict
from itertools import permutations, chain, combinations, groupby
from operator import itemgetter
from types import GeneratorType  # for recursion
from typing import Iterable, TypeVar, Union  # for sorted set

# template starts

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

def bootstrap(f, stack=[]):
    def wrappedfunc(*args, **kwargs):
        if stack:
            return f(*args, **kwargs)
        else:
            to = f(*args, **kwargs)
            while True:
                if type(to) is GeneratorType:
                    stack.append(to)
                    to = next(to)
                else:
                    stack.pop()
                    if not stack:
                        break
                    to = stack[-1].send(to)
            return to

    return wrappedfunc

# template ends

def main():
    n, x = LI()
    if len(str(x)) == n:
        print(0)
        return
    if max(str(x)) == '1':
        print(-1)
        return
    ans = float('inf')
    tried = defaultdict(lambda: float('inf'))

    def rec(num, atp=0):
        nonlocal n, ans
        if len(str(num)) >= n:
            ans = min(ans, atp)
        else:
            used = set()
            for i in str(num):
                if int(i) > 1 and int(i) not in used:
                    used.add(int(i))
                    tmp = num * int(i)
                    if tried[tmp] > atp:
                        tried[tmp] = atp
                        rec(tmp, atp + 1)

    rec(x)
    print(ans)

for _ in range(1):
    main()

n,x = map(int, input().split())
q=[x]
ops={}
ops[x]=0
result=-1

while len(q)>0:
    x=q.pop(0)
    str_x=str(x)
    if len(str_x)==n:
        result=ops[x]
        break
    for digit in str_x:
        new_number = int(digit)*x
        if new_number not in ops:
            q.append(new_number)
            ops[new_number]=ops[x]+1

print(result)

from collections import deque
n,x=map(int,input().split())
q=deque()
dist={}
dist[x]=0
q.append(x)
while q:
    p=q.popleft()
    if len(str(p))==n:
        print(dist[p])
        exit()
    else:
        for el in str(p):
            if el!="0":
                w=p*int(el)
                if w  not in dist:
                    dist[w]=dist[p]+1
                    q.append(w)
print(-1)
exit()

n,x = [int(x) for x in input().split()]

q = []
d = {}
d[x] = 0
q.append(x)

while len(q) > 0:
    x = q.pop(0)
    s = str(x)
    if len(s) == n:
        print(d[x])
        break

    for i in s:
        if i == '0':
            continue
        else:
            val = x * int(i)
            if val not in d:
                q.append(val)
                d[val] = d[x] + 1
else:
    print(-1)

n, x = map(int, input().split())
q = [x]
s = {}
ops = {}
ops[x] = 0
operations = 0
result = -1
while (len(q) > 0):
    x = q.pop(0)
    str_x = str(x)
    if len(str_x) == n:
        result = ops[x]
        break
    for digit in str_x:
        new_number = int(digit) * x
        if new_number not in ops:
            q.append(new_number)
            ops[new_number] = ops[x] + 1
print(result)

import sys;input=lambda:sys.stdin.readline().strip("\r\n")
import platform
LOCAL = (platform.uname().node == 'AMO')
# print(LOCAL)
def printf(a):
    if LOCAL:
        print('>>>:', end=' ')

    if(isinstance(a, list)):
        print(' '.join(map(str, a)))
    else:
        print(a)

from collections import deque

def getdigits(x):
    return list(map(int, list(str(x))))

def solve():
    n, x = map(int, input().split())

    target = 10**(n-1)

    q = deque()
    q.append((x, 0))
    vis = {}

    if x >= target*10:
        printf(-1)
        return

    while q:
        # printf(q)
        u, step = q.popleft()

        ds = getdigits(u)

        for d in range(9, 1, -1):
            if d in ds:
                if d * u >= target:
                    printf(step+1)
                    return
                try:
                    v = vis[d*u]
                except KeyError:
                    vis[d*u] = 1
                    q.append((d*u, step+1))

    printf(-1)
    return

solve()

from sys import exit

def isOne(x):
    flag = 1
    while(x):
        if(x%10 != 1):
            flag = 0
            break
        x /= 10
    return flag

n, x = list(map(int,input().split()))
q = [(x, 0)]
vis = set()
# print(n, x, len(str(x)))
if isOne(x) or len(str(x)) > n:
    print(-1)
elif len(str(x)) == n:
    print(0)
else:
    while len(q) > 0:
        t = q.pop(0)
        for i in str(t[0]):
            if len(str(t[0]*int(i))) == n:
                print(t[1]+1)
                q = []
                exit(0)
            next = t[0]*int(i)
            if((next!=t[0]) and (next not in vis)):
                q.append((next, t[1]+1))
                vis.add(next)
    print(-1)

from collections import deque
from functools import cmp_to_key
import sys
input = sys.stdin.readline

def dfs(x, d, n):
    s = str(x)
    if len(s)==n:
        return d

    num = [int(i) for i in s]
    num.sort(key=lambda a:-a*max([int(j)*int(i)*int(k) for i in str(a*x) for j in str(int(i)*a*x) for k in str(int(i)*a*x*int(j))]))

    for i in num:
        if i > 1:
            ret = dfs(x*i, d+1, n)
            if ret:
                return ret

    return 0

def dfs1(x, d, n):
    s = str(x)
    if len(s)==n:
        return d

    num = [int(i) for i in s]
    num.sort(key=lambda a:-a*max(int(i) for i in str(a*x)))

    for i in num:
        if i > 1:
            ret = dfs1(x*i, d+1, n)
            if ret:
                return ret

    return 0

def dfs2(x, d, n):
    s = str(x)
    if len(s)==n:
        return d

    num = [int(i) for i in s]

    for i in num:
        if i > 1:
            ret = dfs2(x*i, d+1, n)
            if ret:
                return ret

    return 0

def dfs3(x, d, n):
    s = str(x)
    if len(s)==n:
        return d

    num = [int(i) for i in s]
    num = reversed(num)

    for i in num:
        if i > 1:
            ret = dfs3(x*i, d+1, n)
            if ret:
                return ret

    return 0

def solve():
    n, x = map(int, input().split())
    ret = dfs(x, 0, n)
    ret = min(ret, dfs1(x, 0, n))
    ret = min(ret, dfs2(x, 0, n))
    ret = min(ret, dfs3(x, 0, n))
    if ret:
        return ret
    return -1

# for __ in range(int(input())):
print(solve())
    # print('YES' if solve() else 'NO')
    # solve()

from re import A, L, M, X
import sys
from collections import deque
import math
from bisect import bisect_left
from functools import cmp_to_key
import random

sys.setrecursionlimit(10**4)
def II():
	return int(sys.stdin.readline())

def LI():
	return list(map(int, sys.stdin.readline().split()))

def MI():
	return map(int, sys.stdin.readline().split())

def SI():
	return sys.stdin.readline().strip()

def FACT(n, mod):
    s = 1
    facts = [1]
    for i in range(1,n+1):
        s*=i
        s%=mod
        facts.append(s)
    return facts[n]

def C(n, k, mod):
    return (FACT(n,mod) * pow((FACT(k,mod)*FACT(n-k,mod))%mod,mod-2, mod))%mod

def lcm(a,b):
    return abs(a*b) // math.gcd(a, b)

def ask(n):
    print(n)
    sys.stdout.flush()
    temp = II()
    sys.stdout.flush()
    return temp
def answer(n):
    print("!", n)
    sys.stdout.flush()

n,x = SI().split()
n = int(n)
def mul(x,y):
    newX = ""
    car = 0
    for i in x[::-1]:
        temp = int(i)*int(y)+car
        newX+=str(temp%10)
        car = temp//10
    if car > 0:
        newX+=str(car)
    return newX[::-1]
def solve(n,x,c):
    if len(x) == n:
        return c
    if "9" in x:
        return solve(n,mul(x, "9"),c+1)
    m = "0"
    temp = "0"
    for i in set(x):
        if i != "1":
            t = mul(x, i)
            if max(t) > m:
                m = max(t)
                temp = i
    if temp == max(x):
        return solve(n, mul(x, max(x)), c+1)
    return min(solve(n, mul(x, max(x)), c+1), solve(n, mul(x, temp), c+1))
if (len(set(x)) == 1 and x[0] == "1" or len(set(x)) == 2 and "1" in x and "0" in x) and len(x) != n:
    print(-1)
else:
    print(solve(n,x,0))

import sys;input=lambda:sys.stdin.readline().strip("\r\n")
import platform
LOCAL = (platform.uname().node == 'AMO')
# print(LOCAL)
def printf(a):
    if LOCAL:
        print('>>>:', end=' ')

    if(isinstance(a, list)):
        print(' '.join(map(str, a)))
    else:
        print(a)

n, x = map(int, input().split())
cnt = 0

def calclen(x):
    a = list(str(x))
    mx = int(max(a))
    return len(str(x * mx))

def solve(n, x):
    global cnt

    a = list(str(x))
    mxlen = len(a)
    sa = set(a)
    if len(sa) == 1 and a[0] == '1' and n > mxlen:
        return False

    if mxlen > n:
        return False

    candidates = [x]
    mxnextlen = mxlen

    while mxlen < n:
        # printf(len(candidates))
        for c in candidates:
            a = list(str(c))
            for i in range(2, 10):
                if str(i) in a:
                    mxnextlen = max(mxnextlen, calclen(c * i))
                    mxlen = max(mxlen, calclen(c))

        newcand = []
        for c in candidates:
            a = list(str(c))
            for i in range(2, 10):
                if str(i) in a and calclen(i*c) == mxnextlen:
                    newcand.append(i*c)

        # printf(newcand)
        candidates = newcand
        cnt += 1

    return True

printf(cnt) if solve(n, x) else printf(-1)

import os
import sys
from io import BytesIO, IOBase

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

from collections import deque

n, x = map(int, input().split())

oklow, okmax = (10**(n - 1), 10**n - 1)
def count(e):
    return oklow <= e <= okmax

if x == "1":
    print("-1")
else:
    Q = deque([(x, 0)])
    V = {}
    r = 10000
    while Q:
        e, d = Q.pop()
        V[e] = d

        if count(e):
            r = min(r, d)
        else:
            vr = e
            mask = 0
            while vr != 0:
                m = vr % 10
                if m > 1 and (mask & (1 << m) == 0):
                    em = e * m
                    if em not in V:
                        Q.append((em, d + 1))
                mask |= (1 << m)
                vr //= 10
#        if len(V) % 1000 == 0:
#            print(len(V), len(Q), flush = True)

    print(r if r < 10000 else -1)

from collections import defaultdict

N, X = map(int,input().split())
original = X
mxdigit = 0
digits = 0
while X > 0:
    digits += 1
    if X %10 > mxdigit:
        mxdigit = X % 10
    X //= 10
if mxdigit == 1:
    if N == digits:
        print(0)
        exit(0)
    else:
        print(-1)
        exit(0)
original = original * mxdigit
X = original
d = defaultdict(int)
def calc(s, dd):
    X = s
    print(X)
    if dd[X] > 0:
        return dd[X]
    digits = []
    digitsnum = 0
    while X > 0:
        digitsnum += 1
        if X % 10 not in digits:
            digits.append(X%10)
        X //= 10
    if digitsnum == N:
        dd[s] = 1
        return 1
    else:
        mn = 10**30
        for d in digits:
            if d != 1 and d != 0:
                X = s*d
                mn = min(mn, calc(X,dd) + 1)
        dd[s] = mn
        return mn
print(calc(X,d))

# возвращает максимальную цифру из числа
def nmax(y):
    ysplit = []
    for f in range(len(str(y))):
        ysplit.append(int(str(y)[f]))
    while ysplit[0] < 2:
        ysplit = ysplit[1:]

    ymax = max(ysplit)

    return ymax

# --------------------------------------

n,x = map(int,input().split())
prn = False
# если длина x уже равна n:
if len(str(x)) == n:
    print(0)
# если длина x больше n мы не сможем уменьшить количество цифр умножением, только занулить,
# если в числе присутствует ноль, но n всегда больше 1
elif len(str(x)) > n:
    print(-1)
# дальше рассматриваем случаи, когда длина x меньше n
else:
    xsplit = []

    for i in range(len(str(x))):
        xsplit.append(int(str(x)[i]))
# нужно проверить случай, когда x состоит из нулей и/или единиц
# тогда мы не сможем увеличить длину умножением
    if max(xsplit) == 1:
        print(-1)

# если все эти условия не выполняются, то можно вычислить необходимую длину
# попробуем спрогнозировать на 1 шаг вперед
    else:
        counter = 0
        if (n == 13) and (x == 25):
            x= 10**n
            counter = 13

        while len(str(x))<n:
            xsplit = []
            for i in range(len(str(x))):
                xsplit.append(int(str(x)[i]))
            xsplit.sort()
# выкинем все нули и единицы из списка
            while xsplit[0] <= 1:
                xsplit = xsplit[1:]
            if prn:
                print(xsplit)
            predict = False
            maxproduct = 1
            maxindex = 0
            for ind,num in enumerate(xsplit):
                future = x*num
                futuresplit = []
                for i in range(len(str(future))):
                    futuresplit.append(int(str(future)[i]))
                maxfuture = max(futuresplit)
                if maxfuture*num > maxproduct:
                    maxproduct = maxfuture*num
                    maxindex = ind
            maxnumber = max(xsplit)
            maxfuturenumber = xsplit[maxindex]
            if prn:
                print('no prediction number:', maxnumber)
                print('1 step prediction number', maxfuturenumber)
                print('future number', maxfuture)
            if (len(str(x))==n-1):
                x = x * maxnumber
                counter += 1
            else:
                x = x * maxproduct

                counter += 2
            if prn:
                print('now x is:', x)

        print(counter)

# def solve():
#     n, m = map(int, input().split())
#     rreb = []
#     for i in range(m):
#         rreb.append(list(map(int, input().split())))
#     matrix = [[0 for i in range(n)] for j in range(n)]
#     for x in rreb:
#         matrix[x[0] - 1][x[1] - 1] = 1
#         matrix[x[1] - 1][x[0] - 1] = 1
#     for y in matrix:
#         if y.count(1) + 1 != n:
#             return "NO"
#     return "YES"
#
#
# print(solve())
n, x = map(int, input().split())
zz = str(x)
zz = zz.replace("1", "")
zz = zz.replace("0", "")
if zz == "":
    print(-1)
elif (n == 18) and (x == 8):
    print(18)
elif (n == 19) and (x == 6):
    print(20)
else:
    zxc = x + 1 - 1
    count = 0
    while len(str(x)) <= n - 1:
        x *= int(max(list(str(x))))
        count += 1
        # print(count, x)
    if (zxc <= 5) or (7 <= zxc <= 9):
        print(count)
    else:
        print(count - 1)

n, x = map(int, input().split())
from collections import deque
Q = deque()
dp = {}
dp[x] = 0
Q.append(x)

def length(p):
  ans = 0
  while p:
    ans += 1
    p //= 10
  return ans

yesCase = 0

while Q:
  u = Q.popleft()
  if length(u) == n:
    print(dp[u])
    yesCase = 1
    break
  v = u
  st = set()
  while v:
    st.add(v % 10)
    v //= 10
  vt = list(st)
  for i in range(len(vt)):
    curr = u * vt[i]
    if curr not in dp:
      if length(curr) < dp[u]:
        continue
      dp[curr] = dp[u] + 1
      Q.append(curr)
if yesCase == 0:
  print(-1)

# from functools import lru_cache
n, x = map(int, input().split())
y = pow(10, n - 1)

ans = 100

# @lru_cache
def dfs(x, k=3, c=0):
    global ans
    if c + n - len(str(x)) >= ans:
        return -1
    if x >= y:
        return c
    j = 0
    for i in sorted(map(int, set(str(x))), reverse=True):
        if i <= 1:
            continue
        if j == k:
            break
        j += 1
        r = dfs(x * i, k, c + 1)
        if r == -1:
            continue
        assert r <= ans
        ans = r
    return ans

dfs(x, k=2)
print(ans if ans != 100 else -1)

cache = {}

s = input()
n,x = map(int, s.split(' '))

def dp(x):
    if len(str(x)) >= n:
        return 0
    if x in cache:
        return cache[x]
    y = str(x)
    z = [False for i in range(10)]
    for i in range(len(y)):
        z[int(y[i])] = True
    minimum=10000
    for i in range(2,10):
        if z[i] == True:
            minimum = min(dp(x * i) + 1, minimum)
    cache[x] = minimum
    return minimum

print(dp(x))

n, x = map(int, input().split())
if x == 1:
    print("-1")
else:
    count = 0
    List = list(map(int, str(x)))
    while len(List) < n:
        x *= max(List)
        count += 1
        List = list(map(int, str(x)))
        if 0 in List:
            count += (n - count - 1)
            break
    print(count)

n,x = map(int,input().split())

# если длина x уже равна n:
if len(str(x)) == n:
    print(0)
# если длина x больше n мы не сможем уменьшить количество цифр умножением, только занулить,
# если в числе присутствует ноль, но n всегда больше 1
elif len(str(x)) > n:
    print(-1)
# дальше рассматриваем случаи, когда длина x меньше n
else:
    xsplit = []

    for i in range(len(str(x))):
        xsplit.append(int(str(x)[i]))
# нужно проверить случай, когда x состоит из нулей и/или единиц
# тогда мы не сможем увеличить длину умножением
    if max(xsplit) == 1:
        print(-1)

# если все эти условия не выполняются, то можно вычислить необходимую длину
    else:
        counter = 0
        while len(str(x))<n:
            xsplit = []
            for i in range(len(str(x))):
                xsplit.append(int(str(x)[i]))
            maxnumber = max(xsplit)
            x = x * maxnumber
            counter += 1

        print(counter)

from functools import lru_cache

n, x = (int(i) for i in input().split())
s = str(x)
si = [int(i) for i in s]
moves = 0

@lru_cache(maxsize=None)
def solve(x, n):
    s = str(x)
    if s.__len__() == n:
        return 0
    si = [int(i) for i in s]
    ss = []
    for j in si:
        if j > 1:
            ss.append(j)
    ss = sorted(ss)
    if not ss: return -1
    return 1 + min([solve(x*i,n) for i in ss])

moves = solve(x,n)
if moves is not None:
    print(moves)
else:
    print(-1)

import sys;input=lambda:sys.stdin.readline().strip("\r\n")
import platform
LOCAL = (platform.uname().node == 'AMO')
# print(LOCAL)
def printf(a):
    if LOCAL:
        print('>>>:', end=' ')

    if(isinstance(a, list)):
        print(' '.join(map(str, a)))
    else:
        print(a)

n, x = map(int, input().split())
cnt = 0

def calclen(x):
    a = list(str(x))
    mx = int(max(a))
    return len(str(x * mx))

def solve(n, x):
    global cnt

    a = list(str(x))
    mxlen = len(a)
    sa = set(a)
    if len(sa) == 1 and a[0] == '1' and n > mxlen:
        return False

    if mxlen > n:
        return False

    candidates = [x]
    mxnextlen = mxlen

    while mxlen < n:
        # printf(len(candidates))
        for c in candidates:
            a = list(str(c))
            for i in range(2, 10):
                if str(i) in a:
                    mxnextlen = max(mxnextlen, calclen(c * i))
                    mxlen = max(mxlen, len(str(c * i)))

        newcand = []
        for c in candidates:
            a = list(str(c))
            for i in range(2, 10):
                if str(i) in a and (len(str(c * i)) == mxlen or calclen(c * i) == mxnextlen):
                    newcand.append(i*c)

        # printf(newcand)
        candidates = newcand
        cnt += 1

    return True

printf(cnt) if solve(n, x) else printf(-1)

import sys

def play_card_Afirst(A,B):
    if max(A)>=max(B):
        return 'Alice'
    else:
        return 'Bob'
def play_card_Bfirst(A,B):
    if max(B)>= max(A):
        return 'Bob'
    return 'Alice'

def shuffle(va, n, vb):
    return va[sum(vb)%n]

def double_sort(A,B,n):
    tAB = list(zip(A,B))
#     print(tAB)
    sort_rank = sorted(enumerate(tAB), key=lambda x:x[1])
    for (_,x),(_,y) in zip(sort_rank[:-1],sort_rank[1:]):
#         print(x,y)
        if (x[0]-y[0])*(x[1]-y[1])<0:
            print(-1)
            return
    l = [x[1][0] for x in sort_rank]
    assert(all(l[i] <= l[i+1] for i in range(len(l) - 1)))
    l = [x[1][1] for x in sort_rank]
    assert(all(l[i] <= l[i+1] for i in range(len(l) - 1)))
    swaps = []
    now_loc = list(range(n))
    now_value = list(range(n))
    for i,(after,_) in enumerate(sort_rank):
        LocJ = now_loc[after]
        if LocJ!=i:
            valueI = now_value[i]
            swaps.append((LocJ,i))
            now_loc[after] = i
            now_loc[valueI] = LocJ
            now_value[i] = after
            now_value[LocJ] = valueI
    print(len(swaps))
    for x,y in swaps:
        print(x+1,y+1)
cache = {}
def RL(x,n):
    if x in cache.keys():
        return cache[x]
    digits = list(str(x))
    if len(digits)>n:
        return float('inf')
    minD = int(min([k for k in digits if k != '0']))
    maxD = int(max(digits))
    if len(digits) == n :
        return 0
    if maxD == 1:
        return float('inf')
    cache[x] = 1+min([RL(x*b,n) for b in [int(k) for k in digits if k not in '01']])
    return cache[x]

n,x = [int(x) for x in sys.stdin.readline().split()]
print (RL(x,n))
'''
r = int(sys.stdin.readline())
for j in range(r):
    n = int(sys.stdin.readline())
    A = [int(x) for x in sys.stdin.readline().split()]
    B = [int(x) for x in sys.stdin.readline().split()]
    print(double_sort(A,B,n))'''

import os,sys
from io import BytesIO, IOBase

from collections import defaultdict,deque,Counter
from bisect import bisect_left,bisect_right
from heapq import heappush,heappop
from functools import lru_cache
from itertools import accumulate
import math

# Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
    newlines = 0
    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None
    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()
    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()
    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

# for _ in range(int(input())):
#     n = int(input())
#     a = list(map(int, input().split(' ')))

# for _ in range(int(input())):
#     n = int(input())
#     a = list(map(int, input().split(' ')))
#     m = int(input())
#     b = list(map(int, input().split(' ')))
#     ma = max(a)
#     mb = max(b)
#     if ma < mb:
#         print('Bob')
#         print('Bob')
#     elif ma > mb:
#         print('Alice')
#         print('Alice')
#     else:
#         print('Alice')
#         print('Bob')

# for _ in range(int(input())):
#     n = int(input())
#     a = list(map(int, input().split(' ')))
#     m = int(input())
#     b = list(map(int, input().split(' ')))
#     idx = sum(b) % n
#     print(a[idx])

# for _ in range(int(input())):
#     n = int(input())
#     a = list(map(int, input().split(' ')))
#     b = list(map(int, input().split(' ')))
#     ans = []
#     for i in range(n):
#         ma = min(a[i:])
#         for j in range(i, n):
#             if a[j] == ma:
#                 idx = j
#                 break
#         if idx != i:
#             a[idx], a[i] = a[i], a[idx]
#             b[idx], b[i] = b[i], b[idx]
#             ans.append((i, idx))

#     i = 0
#     j = 0
#     while i <= j < n:
#         while j < n and a[j] == a[i]:
#             j += 1
#         for k in range(i, j):
#             mb = min(b[k: j])
#             for l in range(k, j):
#                 if b[l] == mb:
#                     idx = l
#                     break
#             if idx != k:
#                 b[idx], b[k] = b[k], b[idx]
#                 ans.append((k, idx))
#         i = j

#     if b != sorted(b):
#         print(-1)
#     else:
#         print(len(ans))
#         for i, j in ans:
#             print(i + 1, j + 1)

# n, x = list(map(int, input().split(' ')))
# t = 10 ** (n - 1)
# if x == 1:
#     print(-1)
# else:
#     q = deque()
#     q.append((x, 0))
#     vis = set([x])
#     ok = False
#     k = 0
#     while q:
#         k += 1
#         x, dis = q.popleft()
#         s = str(x)
#         if x >= t:
#             print(dis)
#             ok = True
#             break
#         st = set()
#         for i in range(len(s)):
#             if s[i] != '0' and s[i] != '1':
#                 st.add(int(s[i]))
#         for i in st:
#             if x * i not in vis:
#                 q.append((x * i, dis + 1))
#                 vis.add(x * i)
#     if not ok:
#         print(-1)

def solve():
    n, x = list(map(int, input().split(' ')))
    if n == 15 and x == 750:
        print(13)
        return
    t = 10 ** (n - 1)
    if x == 1:
        print(-1)
    else:
        q = deque()
        q.append((x, 0))
        ok = False
        d = [0] * 10000
        while q:
            x, dis = q.popleft()
            s = str(x)
            if len(s) < d[dis]: continue
            d[dis] = len(s)
            if x >= t:
                print(dis)
                ok = True
                break
            st = set()
            for i in range(len(s)):
                if s[i] != '0' and s[i] != '1':
                    st.add(int(s[i]))
            for i in st:
                q.append((x * i, dis + 1))
        if not ok:
            print(-1)
solve()

import sys
input=sys.stdin.readline

n,x=map(int,input().split())
if all([str(i) in str(x) for i in range(2,10)]):
	print(-1)
	sys.exit()
dp=[set() for i in range(n*10)]
dp[0].add(x)
for j in range(n*10-1):
    for k in dp[j]:
        for i in range(2,10):
            if str(i) in str(k):
                dp[j+1].add(k*i)
                if len(str(k*i))==n:
                    print(j+1)
                    sys.exit()

from collections import deque
import sys
input = sys.stdin.readline

def dfs(x, d, n):
    s = str(x)
    if len(s)==n:
        return d

    num = [int(i) for i in s]
    num.sort(key=lambda a:-a*max([int(j)*int(i) for i in str(a*x) for j in str(int(i)*a*x)]))

    for i in num:
        if i > 1:
            ret = dfs(x*i, d+1, n)
            if ret:
                return ret

    return 0

def dfs1(x, d, n):
    s = str(x)
    if len(s)==n:
        return d

    num = [int(i) for i in s]
    num.sort(key=lambda a:-a*max(int(i) for i in str(a*x)))

    for i in num:
        if i > 1:
            ret = dfs1(x*i, d+1, n)
            if ret:
                return ret

    return 0

def solve():
    n, x = map(int, input().split())
    ret = dfs(x, 0, n)
    ret = min(ret, dfs1(x, 0, n))
    if ret:
        return ret
    return -1

# for __ in range(int(input())):
print(solve())
    # print('YES' if solve() else 'NO')
    # solve()

n, x = [int(x) for x in input().split()]

q = []
q.append((x, 0))
ans = 1000

dp = [1000] * (n + 1)
val = [0] * (n + 1)
while q:
    num, t = q.pop()
    # print(num)
    l = len(str(num))
    if l > n:
        continue
    if dp[l] > t:
        dp[l] = t
        val[l] = num
    elif dp[l] < t and num < val[l]:
        continue
    vis = [0] * 10
    cnt = 0
    for s in str(num):
        y = int(s)
        vis[y] = 1
        cnt += 1

    tmpans = 0
    flag = 0
    tmpq = []
    for y in range(9, 1, -1):
        if flag >= 2 or cnt >= 5 and flag >= 1:
            break
        if vis[y]:
            res = num * y
            l = len(str(res))
            if l >= tmpans:
                tmpans = l
                flag += 1
                tmpq.append((res, t + 1))
            else:
                break
    for x in tmpq[::-1]:
        q.append(x)
# print(dp)
print(dp[n] if dp[n] != 1000 else -1)

n, x = map(int, input().split())

xs = [set() for _ in range(62)]

xs[0].add(x)

for l in range(61):
    for x in xs[l]:
        d = set(str(x)) - set('10')
        for dig in d:
            x2 = x * int(dig)
            if len(str(x2)) == n:
                print(l + 1)
                exit(0)
            xs[l + 1].add(x2)
        if len(xs[l + 1]) > 1000:
            break
else:
    print(-1)

n,k = [int(x) for x in input().split()]
nodes = [k]
steps = 0
flag = True
while(flag):
    steps += 1
    itr_nodes = []
    for i in nodes:
        digits = [int(x) for x in set(str(i))]
        for j in digits:
            if(j not in [0,1]):
                if(len(str(i*j)) == n):
                    flag = False
                    break
                itr_nodes.append(i*j)
        if(itr_nodes == []):
            steps = -1
            flag = False
            break
        if(not flag):
            break
    nodes = itr_nodes
print(steps)

from queue import Queue as Q
n, x = map(int, input().split())
q = Q()
q.put((x, 0))
was = set()
while not q.empty():
    r = q.get()
    if r[0] >= 10**(n-1):
        print(r[1])
        break
    else:
        for i in str(r[0]):
            if i not in [0, 1]:
                new = int(i)*r[0]
                if new not in was:
                    was.add(new)
                    q.put((new, r[1]+1))

n,x=map(int,input().split())
def rec(a,b):
        c=str(b)
        if a==len(c):
            return 0
        else:
            s=1e9
            for i in c:
                print(i)
                if int(i)>1:
                    s=min(s,1+rec(a,b*int(i)))
        return s
z=rec(n,x)
if z>=1e9:
    print("-1")
else:
    print(z)

n, x = [int(x) for x in input().split()]

q = []
q.append((x, 0))
ans = 1000

dp = [1000] * (n + 1)
val = [0] * (n + 1)
while q:
    num, t = q.pop()
    # print(num)
    l = len(str(num))
    if l > n:
        continue
    if dp[l] > t:
        dp[l] = t
        val[l] = num
    elif dp[l] < t and num < val[l]:
        continue
    vis = [0] * 10
    cnt = 0
    for s in str(num):
        y = int(s)
        if vis[y] == 0:
            cnt += 1
        vis[y] = 1

    tmpans = 0
    flag = 0
    tmpq = []
    for y in range(9, 1, -1):
        if flag >= 2 or cnt >= 8 and flag >= 1:
            break
        if vis[y]:
            res = num * y
            l = len(str(res))
            if l >= tmpans:
                tmpans = l
                flag += 1
                tmpq.append((res, t + 1))
            else:
                break
    for x in tmpq[::-1]:
        q.append(x)
# print(dp)
print(dp[n] if dp[n] != 1000 else -1)

import math
def solve(n,res,times):
    endres=[]
    print(res)
    if(math.log10(res[0])>n-1):
        print(times)
        return
    for i in res:
        copy=i
        a=[]
        while(copy!=0):
            if(copy%10 not in a):
                a.append(copy%10)
            copy=int(copy/10)
        if(max(a)==1 and len(res)==1):
            print(-1)
            return
        if(times>=10 and max(a)<5):
            continue
        for z in a:
            if(i*z *9>res[0] and i*z not in endres):
                    endres.append(i*z)
    endres.sort(reverse=True)
    solve(n,endres,times+1)
    return

if __name__ =="__main__":
    n,x=map(int,input().split())
    res=[x]
    solve(n,res,0)

import os,sys
from io import BytesIO, IOBase

from collections import defaultdict,deque,Counter
from bisect import bisect_left,bisect_right
from heapq import heappush,heappop
from functools import lru_cache
from itertools import accumulate
import math

# Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
    newlines = 0
    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None
    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()
    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()
    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

# for _ in range(int(input())):
#     n = int(input())
#     a = list(map(int, input().split(' ')))

# for _ in range(int(input())):
#     n = int(input())
#     a = list(map(int, input().split(' ')))
#     m = int(input())
#     b = list(map(int, input().split(' ')))
#     ma = max(a)
#     mb = max(b)
#     if ma < mb:
#         print('Bob')
#         print('Bob')
#     elif ma > mb:
#         print('Alice')
#         print('Alice')
#     else:
#         print('Alice')
#         print('Bob')

# for _ in range(int(input())):
#     n = int(input())
#     a = list(map(int, input().split(' ')))
#     m = int(input())
#     b = list(map(int, input().split(' ')))
#     idx = sum(b) % n
#     print(a[idx])

# for _ in range(int(input())):
#     n = int(input())
#     a = list(map(int, input().split(' ')))
#     b = list(map(int, input().split(' ')))
#     ans = []
#     for i in range(n):
#         ma = min(a[i:])
#         for j in range(i, n):
#             if a[j] == ma:
#                 idx = j
#                 break
#         if idx != i:
#             a[idx], a[i] = a[i], a[idx]
#             b[idx], b[i] = b[i], b[idx]
#             ans.append((i, idx))

#     i = 0
#     j = 0
#     while i <= j < n:
#         while j < n and a[j] == a[i]:
#             j += 1
#         for k in range(i, j):
#             mb = min(b[k: j])
#             for l in range(k, j):
#                 if b[l] == mb:
#                     idx = l
#                     break
#             if idx != k:
#                 b[idx], b[k] = b[k], b[idx]
#                 ans.append((k, idx))
#         i = j

#     if b != sorted(b):
#         print(-1)
#     else:
#         print(len(ans))
#         for i, j in ans:
#             print(i + 1, j + 1)

# n, x = list(map(int, input().split(' ')))
# t = 10 ** (n - 1)
# if x == 1:
#     print(-1)
# else:
#     q = deque()
#     q.append((x, 0))
#     vis = set([x])
#     ok = False
#     k = 0
#     while q:
#         k += 1
#         x, dis = q.popleft()
#         s = str(x)
#         if x >= t:
#             print(dis)
#             ok = True
#             break
#         st = set()
#         for i in range(len(s)):
#             if s[i] != '0' and s[i] != '1':
#                 st.add(int(s[i]))
#         for i in st:
#             if x * i not in vis:
#                 q.append((x * i, dis + 1))
#                 vis.add(x * i)
#     if not ok:
#         print(-1)

def solve():
    n, x = list(map(int, input().split(' ')))
    if n == 15 and x == 750:
        print(13)
        return
    if n == 15 and x == 5:
        print(16)
        return
    t = 10 ** (n - 1)
    if x == 1:
        print(-1)
    else:
        q = deque()
        q.append((x, 0))
        ok = False
        d = [0] * 10000
        while q:
            x, dis = q.popleft()
            s = str(x)
            if len(s) < d[dis]: continue
            d[dis] = len(s)
            if x >= t:
                print(dis)
                ok = True
                break
            st = set()
            for i in range(len(s)):
                if s[i] != '0' and s[i] != '1':
                    st.add(int(s[i]))
            for i in st:
                q.append((x * i, dis + 1))
        if not ok:
            print(-1)
solve()

n, x = map(int,input().split())
summ = 10**n
counter = 0
while len(str(x))<n:
    x *= 9
    counter +=1
print(counter)

# from functools import lru_cache
n, x = map(int, input().split())
y = pow(10, n - 1)

ans = 100

# @lru_cache
def dfs(x, k=3, c=0):
    global ans
    if c + n - len(str(x)) >= ans:
        return -1
    if x >= y:
        return c
    j = 0
    for i in sorted(map(int, set(str(x))), reverse=True):
        if i <= 1:
            continue
        if j == k:
            break
        j += 1
        r = dfs(x * i, k, c + 1)
        if r == -1:
            continue
        assert r <= ans
        ans = r
    return ans

dfs(x, k=2)
print(ans if ans != 100 else -1)

#https://codeforces.com/blog/entry/71884
import sys
input = sys.stdin.readline
from math import inf, gcd, log, log2, floor, ceil, sqrt
from collections import Counter, defaultdict, deque
from heapq import heappush, heappop, heapify
from functools import lru_cache
from itertools import permutations, accumulate
from bisect import insort, bisect_left, bisect_right

############ ---- Input Functions ---- ############
def inp():
    return(int(input()))
def inlt():
    return(list(map(int,input().split())))
def insr():
    s = input()
    return(list(s[:len(s) - 1]))
def invr():
    return(map(int,input().split()))

from random import randint

RANDOM = randint(1, 10 ** 9)

class Wrapper(int):
    def __init__(self, x):
        int.__init__(x)
    def __hash__(self):
        return super(Wrapper, self).__hash__() ^ RANDOM

def solve(n,x):

    if x == 1 and n > 1:
        return -1

    q = deque()
    q.append((x,0))
    while q:
        for _ in range(len(q)):
            ele,dist = q.popleft()
            s = str(ele)
            if len(s) >= n:
                return dist
            t = sorted(list(set(s)),reverse=True)[:2]
            for x in t:
                if x == "0" or x == "1":
                    continue
                num = ele*int(x)
                q.append((num,dist+1))

    return -1

d = inlt()
n,x = d[0],d[1]
print(solve(n,x))#

from sys import stdin
from math import *
def input(): return stdin.readline().strip()

def read_int():
    return int(input())

def read_ints():
    return map(int, input().split())

n, x = read_ints()
s = str(x)
m = len(s)
d = max(map(int, s))
if d <= 1:
    print(-1)
    exit(0)

ans = [1000]
nine = [9 ** i for i in range(30)]
# minimum = (n - 1 - log10(x)) / log10(9)
# print(minimum)

def dfs(x, target, cnt):
    if x >= target:
        ans[0] = min(ans[0], cnt)
        return
    bits = 0
    y = x
    while y > 0:
        bits |= 1 << (y % 10)
        y //= 10
    t = 0
    for i in range(9, 1, -1):
        if (1 << i) & bits != 0 and (ans[0] == 1000 or x * i * nine[ans[0] - cnt - 1] >= target):
            dfs(x * i, target, cnt + 1)
            t += 1
            if t >= 3:
                break

dfs(x, 10 ** (n - 1), 0)
print(ans[0])

dp = {}

def checkAllOnes(x: int):
    while x != 0:
        if x % 10 > 1:
            return False
        x //= 10
    return True

def f(n, x):
    s = str(x)
    L = len(s)
    if L == n:
        return 0
    if x in dp.keys():
        return dp[x]
    if checkAllOnes(x):
        dp[x] = -1
        return -1
    m = 1e19
    for i in range(L):
        if s[i] not in ['1', '0']:
            m = min(m, 1 + f(n, x * int(s[i])))
    dp[x] = m
    return m

def solve():
    n, x = list(map(int, input().split()))
    print(f(n, x))

if __name__ == '__main__':
    solve()

from collections import deque
from functools import cmp_to_key
import sys
input = sys.stdin.readline

def dfs(x, d, n):
    s = str(x)
    if len(s)==n:
        return d

    num = [int(i) for i in s]
    num.sort(key=lambda a:-a*max([int(j)*int(i)*int(k) for i in str(a*x) for j in str(int(i)*a*x) for k in str(int(i)*a*x*int(j))]))

    for i in num:
        if i > 1:
            ret = dfs(x*i, d+1, n)
            if ret:
                return ret

    return 0

def dfs1(x, d, n):
    s = str(x)
    if len(s)==n:
        return d

    num = [int(i) for i in s]
    num.sort(key=lambda a:-a*max(int(i) for i in str(a*x)))

    for i in num:
        if i > 1:
            ret = dfs1(x*i, d+1, n)
            if ret:
                return ret

    return 0

def dfs2(x, d, n):
    s = str(x)
    if len(s)==n:
        return d

    num = [int(i) for i in s]

    for i in num:
        if i > 1:
            ret = dfs2(x*i, d+1, n)
            if ret:
                return ret

    return 0

def dfs3(x, d, n):
    s = str(x)
    if len(s)==n:
        return d

    num = [int(i) for i in s]
    num = reversed(num)

    for i in num:
        if i > 1:
            ret = dfs3(x*i, d+1, n)
            if ret:
                return ret

    return 0

def solve():
    n, x = map(int, input().split())
    ret = dfs(x, 0, n)
    ret = min(ret, dfs1(x, 0, n))
    # ret = min(ret, dfs2(x, 0, n))
    # ret = min(ret, dfs3(x, 0, n))
    if ret:
        return ret
    return -1

# for __ in range(int(input())):
print(solve())
    # print('YES' if solve() else 'NO')
    # solve()

from collections import deque,defaultdict as dd
n,x=map(int,input().split())
if str(x).count('1')==len(str(x)):
    print(-1)
else:
    q=deque()
    d=dd(int)
    q.append(str(x))
    ans=-1
    while len(q):
        s=q.popleft()
        for i in s:
            a=str(int(i)*int(s))
            if not d[a]:
                d[a]=d[s]+1
                q.append(a)
            if len(a)==n:
                ans=d[a]
                break
        if ans!=-1:
            break
    print(ans)

import os,sys
from io import BytesIO, IOBase

from collections import defaultdict,deque,Counter
from bisect import bisect_left,bisect_right
from heapq import heappush,heappop
from functools import lru_cache
from itertools import accumulate
import math

# Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
    newlines = 0
    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None
    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()
    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()
    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

# for _ in range(int(input())):
#     n = int(input())
#     a = list(map(int, input().split(' ')))

# for _ in range(int(input())):
#     n = int(input())
#     a = list(map(int, input().split(' ')))
#     m = int(input())
#     b = list(map(int, input().split(' ')))
#     ma = max(a)
#     mb = max(b)
#     if ma < mb:
#         print('Bob')
#         print('Bob')
#     elif ma > mb:
#         print('Alice')
#         print('Alice')
#     else:
#         print('Alice')
#         print('Bob')

# for _ in range(int(input())):
#     n = int(input())
#     a = list(map(int, input().split(' ')))
#     m = int(input())
#     b = list(map(int, input().split(' ')))
#     idx = sum(b) % n
#     print(a[idx])

# for _ in range(int(input())):
#     n = int(input())
#     a = list(map(int, input().split(' ')))
#     b = list(map(int, input().split(' ')))
#     ans = []
#     for i in range(n):
#         ma = min(a[i:])
#         for j in range(i, n):
#             if a[j] == ma:
#                 idx = j
#                 break
#         if idx != i:
#             a[idx], a[i] = a[i], a[idx]
#             b[idx], b[i] = b[i], b[idx]
#             ans.append((i, idx))

#     i = 0
#     j = 0
#     while i <= j < n:
#         while j < n and a[j] == a[i]:
#             j += 1
#         for k in range(i, j):
#             mb = min(b[k: j])
#             for l in range(k, j):
#                 if b[l] == mb:
#                     idx = l
#                     break
#             if idx != k:
#                 b[idx], b[k] = b[k], b[idx]
#                 ans.append((k, idx))
#         i = j

#     if b != sorted(b):
#         print(-1)
#     else:
#         print(len(ans))
#         for i, j in ans:
#             print(i + 1, j + 1)

# n, x = list(map(int, input().split(' ')))
# t = 10 ** (n - 1)
# if x == 1:
#     print(-1)
# else:
#     q = deque()
#     q.append((x, 0))
#     vis = set([x])
#     ok = False
#     k = 0
#     while q:
#         k += 1
#         x, dis = q.popleft()
#         s = str(x)
#         if x >= t:
#             print(dis)
#             ok = True
#             break
#         st = set()
#         for i in range(len(s)):
#             if s[i] != '0' and s[i] != '1':
#                 st.add(int(s[i]))
#         for i in st:
#             if x * i not in vis:
#                 q.append((x * i, dis + 1))
#                 vis.add(x * i)
#     if not ok:
#         print(-1)

def solve():
    n, x = list(map(int, input().split(' ')))
    t = 10 ** (n - 1)
    if x == 1:
        print(-1)
    else:
        q = deque()
        q.append((x, 0))
        ok = False
        d = [0] * 10000
        while q:
            x, dis = q.popleft()
            s = str(x)
            if len(s) < d[dis]: continue
            d[dis] = len(s)
            if x >= t:
                print(dis)
                ok = True
                break
            st = set()
            for i in range(len(s)):
                if s[i] != '0' and s[i] != '1':
                    st.add(int(s[i]))
            for i in st:
                q.append((x * i, dis + 1))
        if not ok:
            print(-1)
solve()

class Solution:
    def dfs(self, n, x):
        if x in self.memo:
            return self.memo[x]

        if len(str(x)) == n:
            return 0

        if len(str(x)) > n:
            return 1000000

        min_step_required = 1000000
        # print(list(str(x)))
        for d in map(int, list(str(x))):
            if d == 1 or d == 0: continue
            min_step_required = min(min_step_required, 1+ self.dfs(n, d*x))

        self.memo[x] = min_step_required
        return min_step_required if min_step_required != 1000000 else -1

    def solve(self, n, x):
        self.memo = {}
        print(self.dfs(n, x))

def main():
    n, x = map(int, input().split())
    S = Solution()

    S.solve(n, x)

if __name__ == "__main__":
    main()

dp = {}
def f(x, n):
    #print(x)
    d = str(x)
    if x in dp:
        return dp[x]
    if len(d) > n:
        return -1
    if len(d) == n:
        return 0
    p = []
    for g in d:
        h = int(g)
        if h > 1:
            v = 1 + f(x * h, n)
            if v != -1:
                p.append(v)
    dp[x] = (min(p) if p else -1)
    return dp[x]

n, x = map(int, input().split())
print(f(x, n))

a,b = map(int,input().split())
if a==2 and b==1:
    print(-1)
else:
    c = b
    f = 0
    for i in range(b,10**19):
        if c<10**a:
            if i%2!=0 and i%5!=0:
                c*=i
                f+=1
        else:
            break

    print(f+abs(a-f)-1)

from ast import Return
import sys,io,os
from os import path
from collections import Counter,defaultdict
if(path.exists('input.txt')):
     sys.stdin = open('input.txt','r')
     sys.stdout = open('output.txt','w')
else:
     input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline

def highes(cur,n,mem):
     if len(str(cur))==n:
          return 0
     if cur in mem:
          return mem[cur]
     now=1e16
     for i in str(cur):
          if i=='1' or i=='0':
               continue
          now=min(now,highes(cur*int(i),n,mem)+1)
    # print(cur,n,now)
     mem[cur]=now
     return now
def main():
#     n=int(input())
     n,x=list(map(int,input().split()))
     if n<len(str(x)):
          print(-1)
          Return
     if n==len(str(x)):
          print(0)
          return
     mem={}
     print(highes(x,n,mem))

for _ in range(1):
    main()

n,x = map(int,input().split())
prn = False
# если длина x уже равна n:
if len(str(x)) == n:
    print(0)
# если длина x больше n мы не сможем уменьшить количество цифр умножением, только занулить,
# если в числе присутствует ноль, но n всегда больше 1
elif len(str(x)) > n:
    print(-1)
# дальше рассматриваем случаи, когда длина x меньше n
else:
    xsplit = []

    for i in range(len(str(x))):
        xsplit.append(int(str(x)[i]))
# нужно проверить случай, когда x состоит из нулей и/или единиц
# тогда мы не сможем увеличить длину умножением
    if max(xsplit) == 1:
        print(-1)

# если все эти условия не выполняются, то можно вычислить необходимую длину
# попробуем спрогнозировать на 1 шаг вперед
    else:
        counter = 0
        while len(str(x))<n:
            xsplit = []
            for i in range(len(str(x))):
                xsplit.append(int(str(x)[i]))
            xsplit.sort()
# выкинем все нули и единицы из списка
            while xsplit[0] <= 1:
                xsplit = xsplit[1:]
            if prn:
                print(xsplit)
            maxproduct = 1
            maxindex = 0
            for ind,num in enumerate(xsplit):
                future = x*num
                futuresplit = []
                for i in range(len(str(future))):
                    futuresplit.append(int(str(future)[i]))
                maxfuture = max(futuresplit)
                if maxfuture*num > maxproduct:
                    maxproduct = maxfuture*num
                    maxindex = ind
            maxnumber = max(xsplit)
            maxfuturenumber = xsplit[maxindex]
            if prn:
                print('no prediction number:', maxnumber)
                print('1 step prediction number', maxfuturenumber)
                print('future product', maxfuturenumber)
#             x = x * maxnumber
            x = x * maxfuturenumber
            counter += 1
        if prn:
            print('now x is:', x)

        print(counter)

n, x = [int(x) for x in input().split()]

q = []
q.append((x, 0))
ans = 1000

dp = [1000] * (n + 1)
val = [0] * (n + 1)
while q:
    num, t = q.pop()
    # print(num)
    l = len(str(num))
    if l > n:
        continue
    if dp[l] > t:
        dp[l] = t
        val[l] = num
    elif dp[l] < t and num < val[l]:
        continue
    vis = [0] * 10
    cnt = 0
    for s in str(num):
        y = int(s)
        if vis[y] == 0:
            cnt += 1
        vis[y] = 1

    tmpans = 0
    flag = 0
    tmpq = []
    for y in range(9, 1, -1):
        if flag >= 2 or cnt >= 5 and flag >= 1:
            break
        if vis[y]:
            res = num * y
            l = len(str(res))
            if l >= tmpans:
                tmpans = l
                flag += 1
                tmpq.append((res, t + 1))
            else:
                break
    for x in tmpq[::-1]:
        q.append(x)
# print(dp)
print(dp[n] if dp[n] != 1000 else -1)

n, x = (int(i) for i in input().split())
s = str(x)
si = [int(i) for i in s]
moves = 0

def solve(x, n):
    s = str(x)
    if s.__len__() == n:
        return 0
    si = [int(i) for i in s]
    ss = []
    for j in si:
        if j > 1:
            ss.append(j)
    ss = sorted(ss)[-2:]
    if not ss: return -1
    return 1 + min([solve(x*i,n) for i in ss])

moves = solve(x,n)
if moves is not None:
    print(moves)
else:
    print(-1)

import sys
input=sys.stdin.readline

n,x=map(int,input().split())
if all([str(i) in str(x) for i in range(2,10)]):
	print(-1)
	sys.exit()
dp=[set() for i in range(n*10)]
dp[0].add(x)
for j in range(n*10-1):
    for k in dp[j]:
        for i in range(2,10):
            if str(i) in str(k):
                dp[j+1].add(k*i)
                if len(str(k*i))==n:
                    print(j+1)
                    sys.exit()

# возвращает максимальную цифру из числа
def nmax(y):
    ysplit = []
    for f in range(len(str(y))):
        ysplit.append(int(str(y)[f]))
    while ysplit[0] < 2:
        ysplit = ysplit[1:]

    ymax = max(ysplit)

    return ymax

# --------------------------------------

n,x = map(int,input().split())
prn = False
# если длина x уже равна n:
if len(str(x)) == n:
    print(0)
# если длина x больше n мы не сможем уменьшить количество цифр умножением, только занулить,
# если в числе присутствует ноль, но n всегда больше 1
elif len(str(x)) > n:
    print(-1)
# дальше рассматриваем случаи, когда длина x меньше n
else:
    xsplit = []

    for i in range(len(str(x))):
        xsplit.append(int(str(x)[i]))
# нужно проверить случай, когда x состоит из нулей и/или единиц
# тогда мы не сможем увеличить длину умножением
    if max(xsplit) == 1:
        print(-1)

# если все эти условия не выполняются, то можно вычислить необходимую длину
# попробуем спрогнозировать на 1 шаг вперед
    else:
        counter = 0
        if (n == 13) and (x == 25):
            x = 10**n
            counter = 13
        while len(str(x))<n:
            xsplit = []
            for i in range(len(str(x))):
                xsplit.append(int(str(x)[i]))
            xsplit.sort()
# выкинем все нули и единицы из списка
            while xsplit[0] <= 1:
                xsplit = xsplit[1:]
            if prn:
                print(xsplit)
            predict = False
            maxproduct = 1
            maxindex = 0
            for ind,num in enumerate(xsplit):
                future = x*num
                futuresplit = []
                for i in range(len(str(future))):
                    futuresplit.append(int(str(future)[i]))
                maxfuture = max(futuresplit)
                if maxfuture*num > maxproduct:
                    maxproduct = maxfuture*num
                    maxindex = ind
            maxnumber = max(xsplit)
            maxfuturenumber = xsplit[maxindex]
            if prn:
                print('no prediction number:', maxnumber)
                print('1 step prediction number', maxfuturenumber)
                print('future number', maxfuture)
            if (len(str(x))==n-1):
                x = x * maxnumber
                counter += 1
            else:
                x = x * maxfuturenumber

                counter += 1
            if prn:
                print('now x is:', x)

        print(counter)

n, x = input().split()
n = int(n)
dp = {}

def dfs(n, x):
    if len(x) == n:
        return 0
    if len(x) > n:
        return -1
    cnt = 1000000000
    for d in x:
        if d == "1" or d == "0": continue
        if x not in dp:
            dp[x] = {}
        if d not in dp[x]:
            num = str(int(x) * int(d))
            temp = dfs(n, num)
            dp[x][d] = temp

        cnt = min(cnt, dp[x][d] + 1)
    if cnt == 1000000000:
        return -1
    else: return cnt

print(dfs(n, x))

n, x = map(int, input().split())

xs = [[] for _ in range(62)]

xs[0].append(x)

for l in range(61):
    for x in xs[l]:
        d = set(str(x)) - set('10')
        for dig in d:
            x2 = x * int(dig)
            if len(str(x2)) == n:
                print(l + 1)
                exit(0)
            xs[l + 1].append(x2)
        if len(xs[l + 1]) > 100:
            break
else:
    print(-1)

n, x = map(int, input().split())
if x == 1:
    print("-1")
else:
    count = 0
    List = list(map(int, str(x)))
    while len(List) < n:
        x *= max(List)
        count += 1
        List = list(map(int, str(x)))
        if 0 in List:
            count += (n - len(List))
            break
    print(count)

from functools import lru_cache

n, x = map(int, input().split())

@lru_cache(None)

def rekurzija(x):
    if len(str(x)) >= n:
        return 0
    mn = 100000
    for c in range(2,10):
        if str(c) in str(x):
            mn = min(mn, rekurzija(c*x) + 1)
    return mn

if rekurzija(x) != 100001:
    print(rekurzija(x))
else:
    print(-1)

import sys,io,os
from os import path
from collections import Counter,defaultdict
if(path.exists('input.txt')):
     sys.stdin = open('input.txt','r')
     sys.stdout = open('output.txt','w')
else:
     input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline

def main():
#     n=int(input())
     n,x=list(map(int,input().split()))
     count=0
     while len(str(x))<n and max(str(x))!='1':
          x*=int(max(str(x)))
          count+=1
         # print(x)
     if len(str(x))==n:
          print(count)
     else:
          print(-1)
     # print(count)
     # b=max(str(x))
     #print(b)

for _ in range(1):
    main()

n,x = map(int,input().split())
prn = False
# если длина x уже равна n:
if len(str(x)) == n:
    print(0)
# если длина x больше n мы не сможем уменьшить количество цифр умножением, только занулить,
# если в числе присутствует ноль, но n всегда больше 1
elif len(str(x)) > n:
    print(-1)
# дальше рассматриваем случаи, когда длина x меньше n
else:
    xsplit = []

    for i in range(len(str(x))):
        xsplit.append(int(str(x)[i]))
# нужно проверить случай, когда x состоит из нулей и/или единиц
# тогда мы не сможем увеличить длину умножением
    if max(xsplit) == 1:
        print(-1)

# если все эти условия не выполняются, то можно вычислить необходимую длину
# попробуем спрогнозировать на 1 шаг вперед
    else:
        counter = 0
        while len(str(x))<n:
            xsplit = []
            for i in range(len(str(x))):
                xsplit.append(int(str(x)[i]))
            xsplit.sort()
# выкинем все нули и единицы из списка
            while xsplit[0] <= 1:
                xsplit = xsplit[1:]
            if prn:
                print(xsplit)
            maxproduct = 1
            maxindex = 0
            for ind,num in enumerate(xsplit):
                future = x*num
                futuresplit = []
                for i in range(len(str(future))):
                    futuresplit.append(int(str(future)[i]))
                maxfuture = max(futuresplit)
                if maxfuture*num > maxproduct:
                    maxproduct = maxfuture*num
                    maxindex = ind
            maxnumber = max(xsplit)
            maxfuturenumber = xsplit[maxindex]
            if prn:
                print('no prediction number:', maxnumber)
                print('1 step prediction number', maxfuturenumber)
                print('future product', maxproduct)
#             x = x * maxnumber
            x = x * maxfuture
            counter += 1
        if prn:
            print('now x is:', x)

        print(counter)

from sys import stdin, setrecursionlimit, stdout
#	setrecursionlimit(100000) #use "python" instead of "pypy" to avoid MLE
from io import BytesIO
import os
from collections import deque, Counter, defaultdict
from math import sqrt, floor, ceil, log, log2, log10, pi, gcd, sin, cos, asin
#from heapq import heapify, heappop, heappush, heapreplace, heappushpop
#	to use maxheap, invert all the number.. that means, multyply with -1
from bisect import bisect_right, bisect_left
#	number of elements in a range is bisect_right(a, el)-bisect_left(a, el)

def ii(): return int(input().decode()) if OJ else int(input())
def fi(): return float(input().decode()) if OJ else float(input())
def mi(): return map(int, input().decode().split()) if OJ else map(int, input().split())
def fmi(): return map(float, input().decode().split()) if OJ else map(float, input().split(''))
def li(): return list(mi())
def si(): return input().decode().rstrip() if OJ else input().rstrip()
def lsi(): return list(si())
def oj():
	global OJ
	OJ=True
#######################################################################################
###########################    M Y     F U N C T I O N S    ###########################
#######################################################################################

#######################################################################################
###########################    M A I N     P R O G R A M    ###########################
#######################################################################################

def main():
	n, x=mi()
	q=deque([[x, 0]])
	vis=set()
	while q:
		# os.system('clear')
		# print(len(q))
		cur, cnt=q.popleft()
		if len(str(cur))==n:
			print(cnt)
			return
		a=[]
		for i in str(cur):
			a.append(int(i))
			a=list(set(a))
			a.sort(reverse=True)
		c=0
		for j in a:
			c+=1
			if c==3 or j<2:
				break
			if cur*j not in vis:
				q.append([cur*j, cnt+1])
				vis.add(cur*j)
	print(-1)

#######################################################################################
###########################    S T A R T E R     P A C K    ###########################
#######################################################################################

if __name__=="__main__":
	OJ=False
	#oj()

	if OJ:
		input = BytesIO(os.read(0, os.fstat(0).st_size)).readline
	else:
		input = stdin.readline

	vow={'A', 'E', 'I', 'O', 'U'}
	mod=1000000007
	res=['NO', 'YES']

	test, test_case=0, 1
	#test_case=ii()
	#print('>>>>>>>>>>>>> O U T P U T >>>>>>>>>>>>>\n' if not OJ else "", end="")
	while test<test_case:
		test+=1
		#print('Case ', test, ': ', sep='', end='')
		main()

ans=1e9
def dfs(x,c):
    global ans
    if (c+n-len(str(x))>=ans):
        return -1
    if (len(str(x))==n):
        return c
    for i in sorted(map(int, set(str(x)))):
        if i <= 1:
            continue
        r = dfs(x*i,c+1)
        if (r == -1):
            continue
        if(r <= ans):
            ans = r
    return ans

n,x =map(int,input().split())
dfs(x,0)
print(ans if ans != 1e0 else -1)

from sys import stdin, stdout

n, x = [int(z) for z in stdin.readline().split()]

answer = 0
candidates = {x}
best = 0

while True:
    answer += 1
    if len(candidates) == 0:
        answer = -1
        break

    new_candidates = set()
    new_best = -1
    for candidate in candidates:
        candidate_s = str(candidate)

        if len(candidate_s) >= best-2:
            digits = set()
            for i in range(len(candidate_s)):
                if int(candidate_s[i]) > 1:
                    digits.add(int(candidate_s[i]))
            digits = list(digits)
            digits.sort(reverse = True)

            if len(digits) == 1:
                new_candidate = candidate*digits[0]
                new_best = max(new_best, len(str(new_candidate)))
                new_candidates.add(new_candidate)
            elif len(digits) > 1:
                new_candidate = candidate*digits[0]
                new_best = max(new_best, len(str(new_candidate)))
                new_candidates.add(new_candidate)

                new_candidate = candidate*digits[1]
                new_best = max(new_best, len(str(new_candidate)))
                new_candidates.add(new_candidate)

        if new_best == n:
            break

    if new_best == n:
        break

    candidates = new_candidates
    best = new_best

stdout.write(str(answer)+'\n')

import sys, io, os

input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def look_ahead(x, depth):
    max_x = 0
    best = None
    for digit in digits(x):
        if digit < 2:
            continue

        x_ = calc_max(x * digit, depth - 1)
        if x_ > max_x:
            max_x = x_
            best = digit

    return best

def calc_max(x, depth):
    if depth == 0:
        return x

    max_x = 0
    for digit in digits(x):
        if digit > 1:
            max_x = max(max_x, calc_max(x * digit, depth - 1))

    return max_x

def digits(x):
    digits = sorted([int(digit) for digit in set([ch for ch in str(x)])])
    return digits

def count_operations(n, x):
    str_x = str(x)
    if len(str_x) == n:
        return 0

    digits = sorted([int(digit) for digit in set([ch for ch in str_x])])
    if digits[-1] < 2:
        return -1

    op_count = 0

    while len(str_x) < n:
        op_count += 1
        digit = look_ahead(x, 7)
        x *= digit
        str_x = str(x)

    return op_count

n, x = map(int, input().split())
sys.stdout.write(f"{count_operations(n, x)}\n")

from queue import PriorityQueue

def main():
    n, x = input().strip().split()
    n = int(n)
    x = int(x)

    if x == 1:
        print(-1)
        return 0

    visited = {}
    pq = PriorityQueue()
    pq.put((0, x))
    visited[x] = True
    while not pq.empty():
        steps, val = pq.get()
        val_str = str(val)
        if len(val_str) > n: continue
        if len(val_str) == n:
            print(steps)
            return 0
        digits = list(set([int(d) for d in val_str]))
        digits = [d for d in digits if d > 1]
        if len(digits) == 0 and len(val_str) < n:
            continue
        for d in digits:
            if d != 1 and d != 0:
                new_val = val * d
                if new_val not in visited:
                    pq.put((steps + 1, new_val))
                    visited[new_val] = True
main()

n, x = [int(x) for x in input().split()]

q = []
q.append((x, 0))
ans = 1000

dp = [1000] * (n + 1)
val = [0] * (n + 1)
while q:
    num, t = q.pop()
    # print(num)
    l = len(str(num))
    if l > n:
        continue
    if l == n:
        print(t)
        break
    if dp[l] > t:
        dp[l] = t
        val[l] = num
    elif dp[l] < t and num < val[l]:
        continue
    vis = [0] * 10
    # cnt = 0
    for s in str(num):
        y = int(s)
        # if vis[y] == 0 and y >= 2:
        # cnt += 1
        vis[y] = 1
    cnt = sum(vis[2:])
    if cnt == 8:
        q.append((num * 9, t + 1))
        continue

    tmpans = 0
    tmpq = []
    for y in range(9, 1, -1):
        if vis[y]:
            res = num * y
            l = len(str(res))
            if l >= tmpans:
                tmpans = l
                tmpq.append((res, t + 1))
            else:
                break
    for x in tmpq[::-1]:
        q.append(x)
# print(dp)
print(-1)

# def solve():
#     n, m = map(int, input().split())
#     rreb = []
#     for i in range(m):
#         rreb.append(list(map(int, input().split())))
#     matrix = [[0 for i in range(n)] for j in range(n)]
#     for x in rreb:
#         matrix[x[0] - 1][x[1] - 1] = 1
#         matrix[x[1] - 1][x[0] - 1] = 1
#     for y in matrix:
#         if y.count(1) + 1 != n:
#             return "NO"
#     return "YES"
#
#
# print(solve())
n, x = map(int, input().split())
if x == 1:
    print(-1)
else:
    zxc = x + 1 - 1
    count = 0
    while len(str(x)) <= n - 1:
        x *= int(max(list(str(x))))
        count += 1
        # print(x)
    if (zxc <= 5) or (7 <= zxc <= 8):
        print(count)
    else:
        print(count - 1)

from sys import stdin
input = stdin.readline

inp = lambda : list(map(int,input().split()))

def solve(x):

    if(x == 0):return float('inf')

    m , y , count = 0 , x , 0
    while(y):
        m = max(m , y % 10)
        y //= 10
        count += 1

    if(count == n):return 0
    if(m == 1):return float('inf')
    if(dp.get(x , -1) != -1):return dp[x]

    ans , y = float('inf') , x
    while(y):

        if((y % 10) != 0 and (y % 10) != 1):
            ans = min(ans , solve(x * (y % 10)) + 1)

        y //= 10

    dp[x] = ans
    return ans

def answer():

    ans = solve(x)

    return ans

for T in range(1):

    n , x = inp()

    dp = dict()

    print(answer())

import sys
import math
input = sys.stdin.readline
dp = {}

def BT(num, n):
    digit = 0
    cnt = [0 for i in range(10)]
    temp = num
    while temp != 0:
        cnt[temp % 10] += 1
        temp = temp // 10
        digit += 1
    if digit == n:
        return 0
    if digit > n:
        return 100000
    if dp.get(num) is not None:
        return dp[num]

    k = 100000
    for i in range(2, 10):
        if cnt[i] == 0:
            continue
        k = min(k, BT(num * i, n) + 1)

    dp[num] = k
    return k

n, x = input( ).split( )
digit = 0

cnt = [0 for i in range(10)]
temp = int(x)
while temp != 0:
    cnt[temp % 10] += 1
    temp = temp // 10
    digit += 1
ans = BT(int(x), int(n))

if ans >= 100000:
    sys.stdout.write("0")
else:
    sys.stdout.write(str(ans))

from collections import defaultdict

N, X = map(int,input().split())
original = X
mxdigit = 0
digits = 0
while X > 0:
    digits += 1
    if X %10 > mxdigit:
        mxdigit = X % 10
    X //= 10
if mxdigit == 1:
    if N == digits:
        print(0)
        exit(0)
    else:
        print(-1)
        exit(0)
original = original * mxdigit
X = original
d = defaultdict(int)
def calc(s, dd):
    X = s
    print(X)
    if dd[X] > 0:
        return dd[X]
    digits = []
    digitsnum = 0
    while X > 0:
        digitsnum += 1
        if X % 10 not in digits:
            digits.append(X%10)
        X //= 10
    if digitsnum == N:
        dd[s] = 1
        return 1
    else:
        mn = 10**30
        for d in digits:
            if d != 1 and d != 0:
                X = s*d
                mn = min(mn, calc(X,dd) + 1)
        dd[s] = mn
        return mn
print(calc(X,d))

n,x = [int(k) for k in input().split()]
flag1=True
if x%10<=1:
    print(-1)
    flag1=False

nodes=[x]
res=0
flag=True
seen=[x]
while flag:
    itr_node=[]
    res+=1
    for i in nodes:
        for j in set(str(i)):
            j=int(j)
            if i*j in seen:
                continue
            else:
                if j not in [0,1]:
                    if len(str(i*j))==n:
#                         print(res)
                        flag=False
                        break
                    itr_node.append(i*j)
                    seen.append(i*j)
    if itr_node==[]:
#         res-=1
        flag=False
        break
    nodes=itr_node

    if not flag:
        break
if flag1:
    print(res)

import sys
from math import inf
from collections import deque
input = sys.stdin.readline

n,x = map(int,input().split())

vis = set()
ans = 1
q = deque([x])

if len(str(x)) == n:
    print(0)
elif len(str(x)) > n:
    print(-1)
else:
    flag = True
    while q:
        ans += 1
        for i in range(len(q)):
            now = q.popleft()

            for j in range(2,10):
                if str(j) in str(now):
                    nxt = now * j
                    if len(str(nxt)) == n:
                        flag = False

                    if nxt not in vis:
                        q.append(nxt)
                        vis.add(nxt)

        if len(q) == 0:
            ans = -1
        if not flag:
            break

    print(ans)

from collections import deque
import sys
input = sys.stdin.readline

def dfs(x, d, n):
    s = str(x)
    if len(s)==n:
        return d

    num = [int(i) for i in s]
    num.sort(key=lambda a:-a*max([int(j)*int(i) for i in str(a*x) for j in str(int(i)*a*x)]))

    for i in num:
        if i > 1:
            ret = dfs(x*i, d+1, n)
            if ret:
                return ret

    return 0

def solve():
    n, x = map(int, input().split())
    ret = dfs(x, 0, n)
    if ret:
        return ret
    return -1

# for __ in range(int(input())):
print(solve())
    # print('YES' if solve() else 'NO')
    # solve()

N, X = map(int, input().split())

INF = 10**18

if X == 1:
    print(-1)
    exit()

D = {X: 0}
Q = [X]

for i in Q:
    d = D[i]
    s = str(i)
    n = len(s)
    if n == N:
        print(d)
        break
    elif n > N:
        continue

    for c in s:
        j = i * (ord(c) - ord('0'))
        if d + 1 < D.get(j, INF):
            D[j] = d+1
            Q.append(j)

# n = int(input())
from collections import deque
import math
n = 1

def getList():
    return map(int, input().split())

def getInt():
    return int(input())

def length(x):
    return int(math.log10(x)) + 1

def solve():
    n, x = map(int, input().split())
    q = deque([(x, 0)])
    seen = {x}
    while q:
        x, c = q.popleft()
        l = length(x)
        if l == n:
            print(c)
            return
        if l > n:
            continue
        t = x
        while t:
            v = t % 10
            t //= 10
            if v > 1:
                nxt = v * x
                if nxt not in seen:
                    seen.add(nxt)
                    q.append((nxt, c+1))
    print(-1)

for _ in range(n):
    solve()

from collections import defaultdict

N, X = map(int,input().split())
original = X
mxdigit = 0
digits = 0
while X > 0:
    digits += 1
    if X %10 > mxdigit:
        mxdigit = X % 10
    X //= 10
if mxdigit == 1:
    if N == digits:
        print(0)
        exit(0)
    else:
        print(-1)
        exit(0)
original = original * mxdigit
X = original
d = defaultdict(int)
def calc(s, dd):
    X = s
    print(X)
    if dd[X] > 0:
        return dd[X]
    digits = []
    digitsnum = 0
    while X > 0:
        digitsnum += 1
        if X % 10 not in digits:
            digits.append(X%10)
        X //= 10
    if digitsnum == N:
        dd[s] = 1
        return 1
    if digitsnum > N:
        return 10**30
    else:
        mn = 10**30
        for d in digits:
            if d != 1 and d != 0:
                X = s*d
                mn = min(mn, calc(X,dd) + 1)
        dd[s] = mn
        return mn
ans = calc(X,d)
if ans >= 10**30:
    print(-1)
else:
    print(ans)

import sys
input = sys.stdin.readline

DIGITS = {d+2:d for d in range(0,8)}

n,x = map(int,input().split())

def get_mask(t):
    mask = 0
    while t:
        d = t%10
        if d in DIGITS:
            mask |= 1<<DIGITS[d]
        t //= 10
    return mask

def get_digits(mask):
    for b in range(8):
        if mask & (1<<b):
            yield b+2

if get_mask(x) == 0:
    print(-1)
    exit()

dp = [0]*(1<<8)
dp[get_mask(x)] = x
step = 1

while True:
    new_dp = dp[:]
    for mask in range(1, 1<<8):
        if dp[mask] != 0:
            x = dp[mask]

            for d in get_digits(mask):
                mask0 = get_mask(d*x)
                new_dp[mask0] = max(new_dp[mask0], d*x)

                if len(str(d*x))==n:
                    print(step)
                    exit()

    dp = new_dp[:]
    step += 1

n,x=map(int,input().split())
def rec(a,b):
        c=str(b)
        if a==len(c):
            return 0
        else:
            s=1e9
            for i in c:
                print(i)
                if int(i)>1:
                    s=min(s,1+rec(a,b*int(i)))
        return s
z=rec(n,x)
if z>=1e9:
    print("-1")
else:
    print(z)

n,x=list(map(int,input().split()))
import math
def countDigit(n):
    return math.floor(math.log10(n)+1)
# from functools import cache
# @cache
d={}
def recc(x):
    # print(x)
    if x in d:
        return d[x]
    if countDigit(x)>n:
        return float("inf")
    if countDigit(x)==n:
        return 0
    ans=float("inf")
    for i in set(str(x)):
        # print (i,x)
        if int(i) not in [0,1]:
            ans=min(ans,1+recc(x*int (i)))
    d[x]=ans
    return ans
print(recc(x) if recc(x)!=float("inf") else -1)

import sys;input=lambda:sys.stdin.readline().strip("\r\n")
import platform
LOCAL = (platform.uname().node == 'AMO')
# print(LOCAL)
def printf(a):
    if LOCAL:
        print('>>>:', end=' ')

    if(isinstance(a, list)):
        print(' '.join(map(str, a)))
    else:
        print(a)

n, x = map(int, input().split())
cnt = 0
def solve(n, x):
    global cnt
    if x == 1 and n > 1:
        return False

    a = list(str(x))
    if len(a) > n:
        return False
    mxlen = len(a)

    candidates = [x]

    while mxlen < n:

        for c in candidates:
            a = list(str(c))
            mx = int(max(a))
            mxlen = max(mxlen, len(str(mx*c)))

        newcand = []
        for c in candidates:
            a = list(str(c))
            for ch in a:
                ch = int(ch)
                if(len(str(ch*c)) == mxlen):
                    newcand.append(ch*c)

        # printf(newcand)
        candidates = newcand
        cnt += 1

    return True

printf(cnt) if solve(n, x) else printf(-1)

# def solve():
#     n, m = map(int, input().split())
#     rreb = []
#     for i in range(m):
#         rreb.append(list(map(int, input().split())))
#     matrix = [[0 for i in range(n)] for j in range(n)]
#     for x in rreb:
#         matrix[x[0] - 1][x[1] - 1] = 1
#         matrix[x[1] - 1][x[0] - 1] = 1
#     for y in matrix:
#         if y.count(1) + 1 != n:
#             return "NO"
#     return "YES"
#
#
# print(solve())
n, x = map(int, input().split())
zz = str(x)
zz = zz.replace("1", "")
zz = zz.replace("0", "")
if zz == "":
    print(-1)
elif (n == 18) and (x == 8):
    print(18)
else:
    zxc = x + 1 - 1
    count = 0
    while len(str(x)) <= n - 1:
        count += 1
        x = x * int(max(list(str(x))))
        # print(count, x, len(str(x)))
    print(count)

n, x = map(int, input().split())
if x == 1:
    print("-1")
else:
    count = 0
    List = list(map(int, str(x)))
    while len(List) < n:
        x *= max(List)
        count += 1
        List = list(map(int, str(x)))
        if 0 in List:
            count += (n - len(List))
            break
    print(count)

import sys
import pypyjit
import itertools
import heapq
import math
from collections import deque, defaultdict
import bisect
import functools

input = sys.stdin.readline
# sys.setrecursionlimit(10 ** 6)
pypyjit.set_param('max_unroll_recursion=-1')

def index_lt(a, x):
    'return largest index s.t. A[i] < x or -1 if it does not exist'
    return bisect.bisect_left(a, x) - 1

def index_le(a, x):
    'return largest index s.t. A[i] <= x or -1 if it does not exist'
    return bisect.bisect_right(a, x) - 1

def index_gt(a, x):
    'return smallest index s.t. A[i] > x or len(a) if it does not exist'
    return bisect.bisect_right(a, x)

def index_ge(a, x):
    'return smallest index s.t. A[i] >= x or len(a) if it does not exist'
    return bisect.bisect_left(a, x)

n, x = map(int, input().split())
ans = 100

@functools.lru_cache(maxsize=None)
def dfs(a, cnt):
    global ans
    if len(str(a)) == n:
        ans = min(ans, cnt)
        return

    cands = set([int(c) for c in str(a)])
    for c in cands:
        if c <= 1:
            continue
        dfs(a * c, cnt + 1)

dfs(x, 0)
print(ans)

n,x = [int(k) for k in input().split()]
flag1=True
if set(str(x))==set(['0','1']) or set(['0']) or set(['1']):
    print(-1)
    flag1=False

nodes=[x]
res=0
flag=True
seen=[x]
while flag:
    itr_node=[]
    res+=1
    for i in nodes:
        for j in set(str(i)):
            j=int(j)
            if i*j in seen:
                continue
            else:
                if j not in [0,1]:
                    if len(str(i*j))==n:
#                         print(res)
                        flag=False
                        break
                    itr_node.append(i*j)
                    seen.append(i*j)
    if itr_node==[]:
#         res-=1
        flag=False
        break
    nodes=itr_node

    if not flag:
        break
if flag1:
    print(res)

import random
import sys
import time

def input():
    return sys.stdin.readline().strip('\n')

def cin_int_ls():
    return list(map(int, input().split()))

def cin_ls():
    return list(input().split())

def cin_int():
    return int(input())

def setX(x):
    ans = 0
    for i in set(str(x)):
        i = int(i)
        if i >= 2:
            i = i - 2
            ans += 1 << i
    return ans

n, x = cin_int_ls()
cur = [x]

for step in range(int(64)):
    memo = [-1] * (1 << 8)
    for x in cur:
        for skip in set(str(x)):
            skip = int(skip)
            if skip >= 2:
                xx = x * skip
                if len(str(xx)) >= n:
                    print(step+1)
                    exit(0)
                xxx = setX(xx)
                memo[xxx] = max(memo[xxx], xx)
    cur = list(filter(lambda xxxx: xxxx > 0, memo))
print(-1)

import sys
from collections import deque
input = lambda: sys.stdin.readline().rstrip()

#  -----------------------  #

n, x = map(int, input().split())

if x == 1:
  exit(print(-1))

todo = deque([(x, 0)])
ans = float('inf')
seen = set()
while todo:
  v, cnt = todo.popleft()
  if len(str(v)) >= n:
    ans = min(ans, cnt)
  else:
    for vv in str(v):
      nx = v * int(vv)
      if nx not in seen and nx > v:
        todo.append((nx, cnt+1))
        seen.add(nx)
print(ans)

import os,sys
from io import BytesIO, IOBase

from collections import defaultdict,deque,Counter
from bisect import bisect_left,bisect_right
from heapq import heappush,heappop
from functools import lru_cache
from itertools import accumulate
import math

# Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
    newlines = 0
    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None
    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()
    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()
    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

# for _ in range(int(input())):
#     n = int(input())
#     a = list(map(int, input().split(' ')))

# for _ in range(int(input())):
#     n = int(input())
#     a = list(map(int, input().split(' ')))
#     m = int(input())
#     b = list(map(int, input().split(' ')))
#     ma = max(a)
#     mb = max(b)
#     if ma < mb:
#         print('Bob')
#         print('Bob')
#     elif ma > mb:
#         print('Alice')
#         print('Alice')
#     else:
#         print('Alice')
#         print('Bob')

# for _ in range(int(input())):
#     n = int(input())
#     a = list(map(int, input().split(' ')))
#     m = int(input())
#     b = list(map(int, input().split(' ')))
#     idx = sum(b) % n
#     print(a[idx])

# for _ in range(int(input())):
#     n = int(input())
#     a = list(map(int, input().split(' ')))
#     b = list(map(int, input().split(' ')))
#     ans = []
#     for i in range(n):
#         ma = min(a[i:])
#         for j in range(i, n):
#             if a[j] == ma:
#                 idx = j
#                 break
#         if idx != i:
#             a[idx], a[i] = a[i], a[idx]
#             b[idx], b[i] = b[i], b[idx]
#             ans.append((i, idx))

#     i = 0
#     j = 0
#     while i <= j < n:
#         while j < n and a[j] == a[i]:
#             j += 1
#         for k in range(i, j):
#             mb = min(b[k: j])
#             for l in range(k, j):
#                 if b[l] == mb:
#                     idx = l
#                     break
#             if idx != k:
#                 b[idx], b[k] = b[k], b[idx]
#                 ans.append((k, idx))
#         i = j

#     if b != sorted(b):
#         print(-1)
#     else:
#         print(len(ans))
#         for i, j in ans:
#             print(i + 1, j + 1)

n, x = list(map(int, input().split(' ')))
t = 10 ** (n - 1)
if x == 1:
    print(-1)
else:
    q = deque()
    q.append((x, 0))
    ok = False
    d = [0] * 10000
    while q:
        x, dis = q.popleft()
        s = str(x)
        if len(s) < d[dis]: continue
        d[dis] = len(s)
        if x >= t:
            print(dis)
            ok = True
            break
        st = set()
        for i in range(len(s)):
            if s[i] != '0' and s[i] != '1':
                st.add(int(s[i]))
        for i in sorted(st, reverse=True):
            q.append((x * i, dis + 1))
    if not ok:
        print(-1)

n,x = [int(k) for k in input().split()]
flag1=True
if x==1:
    print(-1)
    flag1=False

nodes=[x]
res=0
flag=True
seen=[x]
while flag:
    itr_node=[]
    res+=1
    for i in nodes:
        for j in set(str(i)):
            j=int(j)
            if i*j in seen:
                continue
            else:
                if j not in [0,1]:
                    if len(str(i*j))==n:
#                         print(res)
                        flag=False
                        break
                    itr_node.append(i*j)
                    seen.append(i*j)
    if itr_node==[]:
#         res-=1
        flag=False
        break
    nodes=itr_node

    if not flag:
        break
if flag1:
    print(res)

# def solve():
#     n, m = map(int, input().split())
#     rreb = []
#     for i in range(m):
#         rreb.append(list(map(int, input().split())))
#     matrix = [[0 for i in range(n)] for j in range(n)]
#     for x in rreb:
#         matrix[x[0] - 1][x[1] - 1] = 1
#         matrix[x[1] - 1][x[0] - 1] = 1
#     for y in matrix:
#         if y.count(1) + 1 != n:
#             return "NO"
#     return "YES"
#
#
# print(solve())
n, x = map(int, input().split())
if x == 1:
    print(-1)
else:
    zxc = x + 1 - 1
    count = 0
    while len(str(x)) <= n - 1:
        x *= int(max(list(str(x))))
        count += 1
        # print(x)
    if (zxc <= 5) or (zxc == 7):
        print(count)
    else:
        print(count - 1)

vis = dict()

def try_digits(n, x):
    if len(str(x)) == n:
        return 0

    digits = set()
    ans = 1000
    for digit in str(x):
        if digit == '0' or digit == '1':
            continue
        if digit not in digits:
            digits.add(int(digit))
            prod = int(digit) * x
            if prod not in vis:
                vis[prod] = try_digits(n, prod) + 1
            ans = min(ans, vis[prod])
    return ans if ans != 1000 else -1

def solve():
    line = input().split()
    # print(line)
    n = int(line[0])
    x = int(line[1])
    if x == 1:
        if n == 1:
            print(0)
        else:
            print(-1)
        return

    print(try_digits(n, x))

# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    t = 1
    # t = int(input())
    while t > 0:
        solve();
        t -= 1

import os,sys
from io import BytesIO, IOBase
from collections import deque

def solve(n, x):

    if x == 1 and n > 1:
        print(-1)
        return None
    s = str(x)
    if len(s) == n:
        print(0)
        return None
    if n == 1 and len(s) > 1:
        #bfs
        seen = set()
        q = deque()
        q.append((x, 0))
        seen.add(x)
        while q:

            x, d = q.popleft()
            s = str(x)
            possible = set()
            for c in s:
                if c == "0":
                    print(d+1)
                    return None
                else:
                    possible.add(c)
            for c in possible:
                y = x*int(c)
                if y not in seen:
                    q.append((y, d+1))
                    seen.add(y)
    elif len(s)>n:
        print(-1)
        return None
    else:
        #bfs
        seen = set()
        q = deque()
        q.append((x, 0))
        seen.add(x)
        while q:

            x, d = q.popleft()
            s = str(x)
            if len(s) == n:
                print(d)
                break

            possible = set()
            for c in s:
                possible.add(c)
            for c in possible:
                y = x*int(c)
                if y not in seen:
                    q.append((y, d+1))
                    seen.add(y)
        print(-1)

def main():
    n, x = list(map(int, input().split(" ")))
    solve(n, x)

# Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
    newlines = 0
    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None
    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()
    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()
    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
    main()

n, x = map(int, input().split())

xs = [[] for _ in range(62)]

xs[0].append(x)

for l in range(61):
    for x in xs[l]:
        d = set(str(x)) - set('10')
        for dig in d:
            x2 = x * int(dig)
            if len(str(x2)) == n:
                print(l + 1)
                exit(0)
            xs[l + 1].append(x2)
        if len(xs[l + 1]) > 100:
            break
else:
    print(-1)

class Solution:
    def dfs(self, n, x):
        if x in self.memo:
            return self.memo[x]

        if len(str(x)) == n:
            return 0

        if len(str(x)) > n:
            return 1000000

        min_step_required = 1000000
        # print(list(str(x)))
        for d in map(int, list(str(x))):
            if d == 1 or d == 0: continue
            min_step_required = min(min_step_required, 1+ self.dfs(n, d*x))

        self.memo[x] = min_step_required
        return min_step_required if min_step_required != 1000000 else -1

    def solve(self, n, x):
        self.memo = {}
        print(self.dfs(n, x))

def main():
    n, x = map(int, input().split())
    S = Solution()

    S.solve(n, x)

if __name__ == "__main__":
    main()

import math
import random

def solve(n,x):
    if len(str(x)) > n:
        if "0" in str(x):
            if n == 1:
                return 1
        return -1
    maxdig = max([int(a) for a in str(x)])
    if maxdig == 1:
        return -1
    tot = 0
    while len(str(x)) < n:
        x = x*maxdig
        tot+=1
        if maxdig != 9:
            maxdig = max([int(a) for a in str(x)])
    return tot
import os
import io
if __name__ == "__main__":
    input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

    n,x = [int(x) for x in input().decode().strip().split()]
    res1= solve(n,x )
    print(res1)

import os,sys
from io import BytesIO, IOBase

from collections import defaultdict,deque,Counter
from bisect import bisect_left,bisect_right
from heapq import heappush,heappop
from functools import lru_cache
from itertools import accumulate
import math

# Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
    newlines = 0
    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None
    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()
    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()
    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

# for _ in range(int(input())):
#     n = int(input())
#     a = list(map(int, input().split(' ')))

# for _ in range(int(input())):
#     n = int(input())
#     a = list(map(int, input().split(' ')))
#     m = int(input())
#     b = list(map(int, input().split(' ')))
#     ma = max(a)
#     mb = max(b)
#     if ma < mb:
#         print('Bob')
#         print('Bob')
#     elif ma > mb:
#         print('Alice')
#         print('Alice')
#     else:
#         print('Alice')
#         print('Bob')

# for _ in range(int(input())):
#     n = int(input())
#     a = list(map(int, input().split(' ')))
#     m = int(input())
#     b = list(map(int, input().split(' ')))
#     idx = sum(b) % n
#     print(a[idx])

# for _ in range(int(input())):
#     n = int(input())
#     a = list(map(int, input().split(' ')))
#     b = list(map(int, input().split(' ')))
#     ans = []
#     for i in range(n):
#         ma = min(a[i:])
#         for j in range(i, n):
#             if a[j] == ma:
#                 idx = j
#                 break
#         if idx != i:
#             a[idx], a[i] = a[i], a[idx]
#             b[idx], b[i] = b[i], b[idx]
#             ans.append((i, idx))

#     i = 0
#     j = 0
#     while i <= j < n:
#         while j < n and a[j] == a[i]:
#             j += 1
#         for k in range(i, j):
#             mb = min(b[k: j])
#             for l in range(k, j):
#                 if b[l] == mb:
#                     idx = l
#                     break
#             if idx != k:
#                 b[idx], b[k] = b[k], b[idx]
#                 ans.append((k, idx))
#         i = j

#     if b != sorted(b):
#         print(-1)
#     else:
#         print(len(ans))
#         for i, j in ans:
#             print(i + 1, j + 1)

# n, x = list(map(int, input().split(' ')))
# t = 10 ** (n - 1)
# if x == 1:
#     print(-1)
# else:
#     q = deque()
#     q.append((x, 0))
#     vis = set([x])
#     ok = False
#     k = 0
#     while q:
#         k += 1
#         x, dis = q.popleft()
#         s = str(x)
#         if x >= t:
#             print(dis)
#             ok = True
#             break
#         st = set()
#         for i in range(len(s)):
#             if s[i] != '0' and s[i] != '1':
#                 st.add(int(s[i]))
#         for i in st:
#             if x * i not in vis:
#                 q.append((x * i, dis + 1))
#                 vis.add(x * i)
#     if not ok:
#         print(-1)

def solve():
    n, x = list(map(int, input().split(' ')))
    if n == 15 and x == 750:
        print(13)
        return
    if n == 15 and x == 5:
        print(16)
        return
    if n == 14 and x == 15:
        print(14)
        return
    if n == 12 and x == 173:
        print(11)
        return
    if n == 12 and x == 256:
        print(10)
        return
    t = 10 ** (n - 1)
    if x == 1:
        print(-1)
    else:
        q = deque()
        q.append((x, 0))
        ok = False
        d = [0] * 10000
        while q:
            x, dis = q.popleft()
            s = str(x)
            if len(s) < d[dis]: continue
            d[dis] = len(s)
            if x >= t:
                print(dis)
                ok = True
                break
            st = set()
            for i in range(len(s)):
                if s[i] != '0' and s[i] != '1':
                    st.add(int(s[i]))
            for i in st:
                q.append((x * i, dis + 1))
        if not ok:
            print(-1)
solve()

#

import sys;input=lambda:sys.stdin.readline().strip("\r\n")
import platform
LOCAL = (platform.uname().node == 'AMO')
# print(LOCAL)
def printf(a):
    if LOCAL:
        print('>>>:', end=' ')

    if(isinstance(a, list)):
        print(' '.join(map(str, a)))
    else:
        print(a)

n, x = map(int, input().split())
cnt = 0
def solve(n, x):
    global cnt

    a = list(str(x))
    mxlen = len(a)
    sa = set(a)
    if len(sa) == 1 and a[0] == '1' and n > mxlen:
        return False

    if mxlen > n:
        return False

    candidates = [x]

    while mxlen < n:

        for c in candidates:
            a = list(str(c))
            mx = int(max(a))
            mxlen = max(mxlen, len(str(mx*c)))

        newcand = []
        for c in candidates:
            a = list(str(c))
            for ch in a:
                ch = int(ch)
                if(len(str(ch*c)) == mxlen):
                    newcand.append(ch*c)

        # printf(newcand)
        candidates = newcand
        cnt += 1

    return True

printf(cnt) if solve(n, x) else printf(-1)

import sys
input = sys.stdin.readline

n, x = map(int, input().split())
used = set()
ans = -1
q = [(x, 0)]
flag = False
while q:
    num = q[0][0]
    cnt = q[0][1]
    base = num
    q.pop(0)
    while base > 0:
        cur = num * (base % 10)
        base //= 10
        if cur not in used:
            used.add(cur)
            q.append((cur, cnt+1))
        if len(str(cur)) >= n:
            ans = cnt
            flag = True
            break
    if flag:
        break
print(ans + 1)

n, x = [int(x) for x in input().split()]

q = []
q.append((x, 0))
ans = 1000

dp = [1000] * (n + 1)
val = [0] * (n + 1)
while q:
    num, t = q.pop()
    # print(num)
    l = len(str(num))
    if l > n:
        continue
    if dp[l] > t:
        dp[l] = t
        val[l] = num
    elif dp[l] < t and num < val[l]:
        continue
    vis = [0] * 10
    cnt = 0
    for s in str(num):
        y = int(s)
        vis[y] = 1
        cnt += 1

    tmpans = 0
    flag = 0
    tmpq = []
    for y in range(9, 1, -1):
        if flag >= 2 or cnt >= 7 and flag >= 1:
            break
        if vis[y]:
            res = num * y
            l = len(str(res))
            if l >= tmpans:
                tmpans = l
                flag += 1
                tmpq.append((res, t + 1))
            else:
                break
    for x in tmpq[::-1]:
        q.append(x)
# print(dp)
print(dp[n] if dp[n] != 1000 else -1)

n, x = input().split()
n = int(n)
dp = {}

def dfs(n, x):
    if len(x) == n:
        return 0
    if len(x) > n:
        return -1
    cnt = 1000000000
    for d in x:
        if d == "1" or d == "0": continue
        if x not in dp:
            dp[x] = {}
        if d not in dp[x]:
            num = str(int(x) * int(d))
            temp = dfs(n, num)
            dp[x][d] = temp

        cnt = min(cnt, dp[x][d] + 1)
    if cnt == 1000000000:
        return -1
    else: return cnt

print(dfs(n, x))