import sys
def is_prime2(q,k=100):
    q = abs(q)
    if q == 2: return True
    if q < 2 or q&1 == 0: return False
    for i in xrange(3,k):
        x,y = q,i
        while y:
            x, y =  y, x % y
        if x != 1: continue
        if pow(i, q-1, q) != 1:
            return False
    return True
if __name__ == "__main__":

    while True:
        n = input()
        if (n == 0):
            break
        if (n < 19):
            print 13
        else:
            tmp = int((n - 19) / 30)
            if tmp == 0:
                print 19
            while tmp > 0:
                x = 30 * tmp + 19
                if (is_prime2(x) and is_prime2(x - 2) and is_prime2(x - 6) and is_prime2(x - 8)):
                    print x
                    break
                tmp -= 1
                break