import math
import bisect

primes=[2]
top=2
nlist=[2*x-1 for x in range(2, 10000000/2)]
while top<math.sqrt( 10000000):
    top=nlist[0]
    primes.append(top)
    newnlist=[]
    for i in nlist:
        if i%top!=0:
            newnlist.append(i)
    nlist=newnlist
primes=primes+nlist
#print (primes)
while(1):
    n=int(raw_input())
    if n==0:
        break
    else:
        i=bisect.bisect(primes,n)
        while(1):
            i=i-1
            if primes[i]==primes[i-1]+2:
                if primes[i-1]==primes[i-2]+4:
                    if primes[i-2]==primes[i-3]+2:
                        print primes[i]
                        break