#include <iostream>
using namespace std;
bool prime[10000001];
const int MAX = 10000000;
int main(){
	int n;
	bool f;
	for(int i = 0;i <= MAX;++i){
		if(i % 2 == 0) prime[i] = false; 
		else prime[i] = true;
	}
	prime[2] = true;
	prime[1] = false;
	for(int i = 3;i <= MAX;++i){
		if(prime[i]){
			for(int j = 2;j <= MAX/i;++j){
				prime[i*j] = false;
			}
		}
	}
	while(cin >> n,n){
		f = false;
		for(;!f;--n){
			if(prime[n] == true && prime[n - 2] == true && prime[n - 8] == true && prime[n - 6] == true) f = true;
		}
		cout << n+1 << endl;	
	}
	return 0;
}