#include <vector>
#include <iostream>
#include <algorithm>

using namespace std;

vector<bool> dp, searched;

bool is_prime(int n)
{
	if (searched[n])
	{
		return dp[n];
	}

	return isprime(n, 2);
}

bool isprime(int n, int k)
{
	if (n < k * k)
	{
		searched[n] = true;
		
		dp[n] = true;
		
		return true;
	}

	if (n % k == 0)
	{
		searched[n] = true;
		
		dp[n] = false;
		
		return false;
	}

	if (k > 2)
	{
		return isprime(n, k + 2);
	}

	return isprime(n, k + 1);
}

int main()
{
	int N;

	dp = searched = vector<bool>(10000001, false);

	while (true)
	{
		cin >> N;

		if (N == 0) { break; }

		int Ans = 1145141919;

		if (N % 2 == 0)
		{
			N -= 1;
		}

		for (int i = N; ; i -= 2)
		{
			if (is_prime(i - 8) && is_prime(i - 6) && is_prime(i - 2) && is_prime(i))
			{
				Ans = i; break;
			}
		}
		
		cout << Ans << endl;
	}

	return 0;
}