from math import sqrt from collections import deque def h(n): while n>9: n=sum(map(int,str(n))) return n def prime(max): max2 = (max-3)/2 sieve = [True]*(max2+1) for i in range(int((sqrt(max)-3)/2)+1): if not sieve[i]: continue k = i+i+3 j = k*(i+1)+i while j <= max2: sieve[j] = False j += k sieve = [2]+[i+i+3 for i in range(max2+1) if sieve[i]] return sieve k=input() n=input() a=deque() cnt=[0]*10 max=0 ans=0 for i,j in [(i,h(i)) for i in prime(n) if i>=k]: a.append((i,j)) cnt[j]+=1 while cnt[j]>1:cnt[a.popleft()[1]]-=1 size=sum(cnt) if max<=size: max=size ans=a[0][0] print ans