import java.lang.Math.sqrt

fun main(args:Array<String>?): Unit {
    val prime = primes(10_000_000)
    val yotsugo = (3 until prime.size).filter{i -> prime[i] - 8 == prime[i - 3] && prime[i - 2] - 2 == prime[i - 1] - 6 && prime[i - 3] == prime[i - 1] - 6}.map{prime[it]}.toIntArray()
    while(true){
        val n = readLine()!!.trim().toInt()
        if (n == 0) return
        println(yotsugo[upperBound(yotsugo, n) - 1])
    }
}
fun upperBound(array: IntArray, target: Int): Int {
    var left = 0
    var right = array.size
    while(left < right){
        val mid = (left + right) / 2
        if (array[mid] <= target){
            left = mid + 1
        }else {
            right = mid
        }
    }
    return right
}

fun primes(upper: Int): IntArray {
    val isPrime = BooleanArray(upper + 1){true}
    for (p in 2 .. sqrt(upper.toDouble()).toInt()) if (isPrime[p]) {
        for (i in p * p .. upper step p) {
            isPrime[i] = false
        }
    }
    return (2 .. upper).filter(isPrime::get).toIntArray()
}
