primes = [0, 0] + [1] * 9999999
for i in range(2, 3163):
    if primes[i]:
        for j in range(i*i, 10000001, i):
            primes[j] = 0

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