#include<iostream>
#include<cstring>

char p[10000001];

void sieve()
{
	memset( p, 1, sizeof( p ) );
	p[0] = p[1] = 0;

	for( int i = 2; i <= 10000000; ++i )
		if( p[i] )
			for( int j = i * 2; j <= 10000000; j += i )
				p[j] = 0;

	return;
}

int main()
{
	sieve();

	int n;
	while( std::cin >> n, n )
	{
		while( true )
		{
			if( p[n] && p[n-2] && p[n-6] && p[n-8] )
			{
				std::cout << n << std::endl;
				break;
			}

			--n;
		}
	}

	return 0;
}