import math
def sieve(n):
    sieve = [1 for i in range(n + 1)]
    sieve[0] = 0
    sieve[1] = 0
    for i in range(2, int(math.sqrt(n)) + 1):
        if sieve[i] == 1:
            for j in range(2 * i, n, i):
                sieve[j] = 0
    return sieve

while True:
    n = input()
    if n == 0:
        break
    prime = sieve(n)
    for i in range(n, 0, - 1):
        if (prime[i] and prime[i - 2] and prime[i - 6] and prime[i - 8]):
            print i
            break
    
            
        