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
    while not (primes[n] & primes[n-2] & primes[n-6] & primes[n-8]):
        n -= 1
    print(n)