using System;
using System.Linq;

namespace _0222
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] prime = new int[664579];
            prime[0] = 2;
            int count = 1;
            for (int i = 3; i <= 9999991; i += 2)
            {
                bool b = true;
                for (int j = 0; j < count && prime[j] <= Math.Sqrt(i) && b; j++)
                {
                    if (i % prime[j] == 0)
                    {
                        b = false;
                    }
                }
                if (b)
                {
                    prime[count] = i;
                    count++;
                }
            }
            while (true)
            {
                int n = int.Parse(Console.ReadLine());
                if (n == 0)
                {
                    break;
                }
                bool b = true;
                for (int i = n; b; i--)
                {
                    if (prime.Contains(i) && prime.Contains(i - 2) && prime.Contains(i - 6) && prime.Contains(i - 8))
                    {
                        Console.WriteLine(i);
                        b = false;
                    }
                }
            }
        }
    }
}