#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

#define rep(i,n) for(int (i)=0; (i)<(n);++(i))

const int nmax=10000000;

bool isprime[nmax+1];
vector<int> ans;

void init(){
	rep(i,nmax+1) isprime[i]=true;
	isprime[0]=isprime[1]=true;
	for(int i=2;i*i<=nmax;++i)
		if(isprime[i])
			for(int j=i*i;j<=nmax;j+=i)
				isprime[j]=false;

	for(int i=13;i<=nmax;i+=2){
		if(!isprime[i])
			continue;
		if(!isprime[i-2])
			continue;
		if(!isprime[i-6])
			continue;
		if(!isprime[i-8])
			continue;
		ans.push_back(i);
	}
}

int main(void){
	init();
	int in;
	while(cin >> in,in){
		int out=upper_bound(ans.begin(),ans.end(),in)-ans.begin();
		cout << ans[out-1] << endl;
	}
	return 0;
}