#include<iostream>

#define loop(i,a,b) for(int i=a;i<b;i++)
#define rep(i,a) for(int i=0;i<a;i++)


using namespace std;
bool prime[10000001];


int main(){
	rep(i, 10000001){
		prime[i] = true;
	}
	prime[0] = prime[1] = false;

	loop(i, 2, 10001){
		if (prime[i]){
			for (int j = i * 2; j < 10000001; j += i){
				prime[j] = false;
			}
		}
	}



	int ord;
	while (1){
		cin >> ord;
		if (ord == 0){
			break;
		}
		while (ord){
			if (prime[ord] && prime[ord - 2] && prime[ord - 6] && prime[ord - 8]){
				cout << ord << endl;
				break;
			}
			else{
				ord--;
			}
		}
	}




}