#include <iostream>

using namespace std;

const unsigned long Max = 10000000;
bool data[Max + 1];

void eratos(){
	for( int i = 0;i <= Max;i++ ) data[i] = true;

	data[0] = data[1] = false;

	for( int i = 2;i * i <= Max;i++ ) if( data[i] ) for( int j = 2;i * j <= Max;j++ ) data[ i * j ] = false;
}

int main(int argc, char const* argv[])
{
	eratos();

	int n;
	while( cin >> n && n != 0 ){
		for( int i = n;i >= 13;i-- ){
			if( data[i] == true && data[i - 2] == true && data[i - 6] == true && data[i - 8] == true ){
				cout << i << endl;
				break;
			}
		}
	}

	return 0;

}