import math
N=10000000
prime=[1]*(N+1)
prime[0],prime[1]=0,0
for i in range(2,int(math.sqrt(N))):
    if prime[i]==1:
        j=i
        while i*j<=N:
            prime[i*j]=0
            j+=1

while True:
    n=input()
    if n==0:break
    for i in range(n,2,-1):
        if prime[i]==prime[i-2]==prime[i-6]==prime[i-8]==1:
            print i
            break