import sys

def is_prime(q):
    q = abs(q)
    if q == 2:
        return True
    if q < 2 or q & 1 == 0:
        return False
    return pow(2, q - 1, q) == 1
    
if __name__ == "__main__":
    while True:
        print "hoge"
    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_prime(x) and is_prime(x - 2) and is_prime(x - 6) and is_prime(x - 8)):
                    print x
                    break
                tmp -= 1
            
                
                
                