using System;

public class p0222
{
	const int mx = 10000000;
	p0222 ()
	{
		string str;
		int n;
		bool[] prime = new bool[mx];
		for (int i = 0; i < mx; ++i)
			prime [i] = true;
		prime [0] = prime [1] = false;
		
		for (int i = 2; i < mx; ++i)
			if (prime [i])
				for (int j = i+i; j < mx; j+=i)
					prime [j] = false;
		
		while ((str=Console.ReadLine()) != null) {
			n = int.Parse (str);
			if (n == 0)
				break;
			for (int i = n; i >= 13; --i)
				if (prime [i - 8] && prime [i - 6] && prime [i - 2] && prime [i]) {
				Console.WriteLine ("{0}", i);
				break;
				}
		}
	}
	public static int Main(string[] args){
		new p0222();
		return 0;
	}
}