require 'prime'
if true then
  fh=STDIN
else
  fh=open("in0222.txt")
end

ns=[]
while true
  n=fh.gets.chomp.to_i
  break if n==0
  ns.push n
end

nmax=ns.max

p1=Prime.each(nmax).to_a.reverse
fh=open("xxx")
ns.each{|m|
  0.upto(p1.length-4){|i|
    if 
p1[i]<=m and (p1[i+1]==p1[i]-2) and (p1[i+2]==p1[i]-6) and (p1[i+3]==p1[i]-8) then
      puts p1[i]
      break
    end
  }

}