while True:
    N = input()
    if not N:
        break
    prime = [0, 0, 1] + [-1] * (N + 10)
    for i in range(2, N + 1):
        if prime[i] != -1:
            continue
        prime[i] = 1
        for j in range(i + i , N + 1, i):
            prime[j] = 0

    n = 0
    a = 0
    for i in range(8, N + 1):
        print(i, prime[i - 8], prime[i - 6], prime[i - 2], prime[i])
        if prime[i - 8] and prime[i - 6] and prime[i - 2] and prime[i]:
            a = max(a, i)
    print(a)