#include <iostream>
using namespace std;
#define MAX 10000001

bool p[MAX];

int main()
{
	for (int i=0; i<MAX; i++)
		p[i] = 1;

	p[0] = p[1] = 0;
	for (int i=2; i*i<MAX; i++)
		if (p[i])
			for (int k=i+i; k<MAX; k+=i)
				p[k] = 0;

	int N;
	while (cin >> N, N)
	{
		for (int n=N; n>=0; n--)
		{
			if (p[n]&&p[n-2]&&p[n-6]&&p[n-8])
			{
				cout << n << endl;
				break;
			}
		}
	}

	return 0;
}