#include <iostream>
#include <cstring>
//#include <fstream>

const int N = 10000000;

bool prime[N+1];

using namespace std;

void make_prime (void )
{
	memset (prime, true, sizeof (prime ) );

	prime[0] = false;
	prime[1] = false;

	for (int i = 2; i*i <= N; ++i){
		if (prime[i] ) {
			for (int j = i*i; j <= N; j += i ){
				prime[j] = false;
			} // end for
		} // end if	
	} // end for
}
	
int main()
{
//	cut here before submit 
//	freopen ("testcase.primequad", "r", stdin );

	make_prime();

	int n;
	while (cin >> n && n ){
		for (int i = n; i >= 13; --i ){
			if (prime[i] && prime[i-2] && prime[i-6] && prime[i-8] ){
				cout << i << endl;
				break;
			} // end if
		} // end for
	} // end loop
		
	return 0;
}