#include <iostream>
#include <vector>
#include <cmath>
using namespace std;

bool p[10000001];
vector<int> plist,p4;

void prime(){
	p[0] = true;
	p[1] = true;
	for(int i = 4;i < 10000001;i += 2){
		p[i] = true;
	}
	for(int i = 3;i < sqrt(10000001) + 1;i++){
		for(int j = i * 2;j < 10000001;j += i){
			p[j] = true;
		}
	}
	for(int i = 0;i < 10000001;i++){
		if(!p[i]) {
			plist.push_back(i);
		}
	}
	for(int i = 0;i < plist.size() - 3;i++){
		if(plist[i + 3] - plist[i] == 8 && plist[i + 2] - plist[i] == 6 && plist[i + 1] - plist[i] == 2) p4.push_back(plist[i + 3]);
	}
}

int main(){
	int n;
	prime();
	while(cin >> n,n){
		bool flag = false;
		for(int i = 0;i < p4.size();i++) {
			if(p4[i] > n){
				cout << p4[i - 1] << endl;
				flag = true;
				break;
			}
		}
		if(!flag) cout << p4[p4.size() - 1] << endl;
	}
	return 0;
}