import Control.Applicative ((<$>))
import Control.Monad (unless)

main :: IO ()
main = do
  n <- readLn
  unless (n == 0) $ do
    solve n >>= print
    main

solve :: Int -> IO Int
solve = return . f []
  where f st x | even x = f st (x-1)
               | isPrime x = case st of
                              (a : b : c : _) -> if x + 2 == a && a + 4 == b && b + 2 == c then c else f [x, a, b] (x - 2)
                              _ -> f (x:st) (x - 2)
               | otherwise = f st (x - 2)

isPrime :: Int -> Bool
isPrime n | n == 1 = False
          | n == 2 = True
          | even n = False
          | otherwise = all ((/= 0) . (mod n)) ls
  where
    ls = takeWhile ((<= n) . (^ 2)) [3, 5 ..]

