### constant

MAX_P = 10000000

### subroutines

def gen_primes(max_p)
  primes = Array.new(max_p + 1){true}
  primes[0] = primes[1] = false

  s_max_p = Math.sqrt(max_p + 0.5).to_i

  for p in (2..s_max_p)
    if primes[p]
      for q in (p * p).step(max_p, p)
        primes[q] = false
      end
    end
  end

  return primes
end

### main

primes = gen_primes(MAX_P)

while true
  n = gets.strip.to_i
  break if n == 0

  n.downto(13).each do |k|
    if primes[k] && primes[k - 2] && primes[k - 6] && primes[k - 8]
      puts k
      break
    end
  end
end