require 'prime'
primes = Prime.each(10_000_000).to_a
quad = []
primes.each_cons(4) do |x, _, _, y|
    quad << y if y - x == 8
end
loop do
    n = gets.to_i
    break if n == 0
    i = (0..quad.size-1).bsearch {|i| quad[i] > n}
    puts i ? quad[i - 1] : quad[-1]
end
