using System;

public class p0222{
	const int mx = 10000001;

	p0222 ()
	{
		int n;
		string str;
		bool[] prm = new bool[mx];
		for(int i = 2; i < mx; ++i) prm[i] = true;

		for(int i = 2; i < mx; ++i)
			if(prm[i])
				for(int j = i+i; j < mx; j += i) prm[j] = false;

		while ((str=Console.ReadLine()) != null && str != "0") {
			n = int.Parse(str.Trim ());
			do {
				if(prm[n] && prm[n-2] && prm[n-6] && prm[n-8]){
					Console.WriteLine("{0}", n);
					break;
				}
			} while(13 < n--);
		}
	}

	public static int Main(string[] args){
		new p0222();
		return 0;
	}
}