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

while True:
    n = int(input())
    if n == 0:
        break
    while True:
        if primes[n-8] and primes[n-6] and primes[n-2] and primes[n]:
            print(n)
            break
        else:
            n -= 1