move = [[[10, 10], [4, 4]], [[8, 2],[4, 2]]]

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

while 1:
    n = int(input())

    if not n: break
    n -= (n%2 == 0)
    while n >= 13:
        if sos[n] and sos[n-2] and sos[n-6] and sos[n-8]:
            print(n)
            break
        else:
            n -= move[sos[n-8]][sos[n-6]][sos[n-2]]
# measure_stop = datetime.now()
# print(measure_stop - measure_start)