require 'prime'

if true then
  fh=STDIN
else
  fh=open("in0222.txt")
end
#max=10000000
max= 10000000

#primes = (2..Math.sqrt(max)).to_a.inject((2..max).to_a){
#  |nums, s| nums.reject{|n| n!=s && n%s==0}}.reverse
#  p = Prime.each(n).reverse
#h=Hash.new

while true
  n=fh.gets.chomp.to_i
  break if n==0
  n.downto(13) {|i|
    if Prime.prime?(i) and Prime.prime?(i-2) and Prime.prime?(i-6) and Prime.prime?(i-8) then
      puts i
      break
    end
  }
end