def p(n):
	if n%2==0:
		return False
	for i in xrange(3,int(n**0.5)+1,2):
		if n%i==0:
			return False
	else:
		return True
		
while 1:
	n=input()
	if n==0:break
	for i in xrange(n,11,-1):
		if p(i) and p(i-2) and p(i-6) and p(i-8):
			print i
			break