MAX_N = 10000000+1
SQRT_MAX = 3163
sos = [1] * (MAX_N+1)
for i in range(2, SQRT_MAX+1):
    if sos[i]:
        for j in range(i+i, MAX_N+1, i):
            sos[j] = 0

while 1:
    try:
        n = int(input())

        if not n: break
        for i in reversed(range(13, n+1)):
            if sos[i] and sos[i-2] and sos[i-6] and sos[i-8]:
                print(i)
                break
    except:
        pass