def get_quad(n, p):
    for ni in range(n,0,-1):
        if p[ni] and p[ni - 2] and p[ni - 6] and p[ni - 8]:
            return ni
def sieve(n):
    p = [1] * (n + 1)
    p[0] = p[1] = 0
    
    for i in range(int(n ** 0.5) + 1):
        if p[i]:
            for j in range(2 * i, len(p), i):
                p[j] = 0
    return p
import sys
f = sys.stdin

n = []
while True:
    ni = int(f.readline())
    if ni == 0:
        break
    n.append(ni)

prime = sieve(max(n))
for ni in n:
    print(get_quad(ni, prime))