#include <iostream>
using namespace std;
bool t[10000000] = {false};
int main()
{
	int n, i, j;
	t[0] = true;
	for (i = 2; i * i <= 10000000; i++)
	{
		if (!t[i-1])
		{
			for (j = i+i; j <= 10000000; j+=i)
				t[j-1] = true;
		}
	}
	while (cin >> n, n)
	{
		for (; n >= 13; n--)
		{
			if (!t[n-9] && !t[n-7] && !t[n-3] && !t[n-1])
				break;
		}
		cout << n << endl;
	}
}