r=10000000
sqrt=int(r**0.5)
p=[1]*r
p[0]=0
p[3::2]=[0 for i in xrange(3,r,2)]
for i in xrange(2,sqrt,2):
	if p[i]:
		p[2*i+1::i+1]=[0 for x in range(2*i+1,r,i+1)]

while 1:
	n=input()
	if n==0:break
	for i in xrange(n-1,11,-1):
		if p[i] and p[i-2] and p[i-4] and p[i-6]:
			print i+1
			break