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

bool prime[10000010];

int main() {
	for(int i = 0; i < 10000010; i++) prime[i] = true;
	prime[0] = prime[1] = false;
	for(int i = 2; i < 10000010; i++) {
		if(prime[i]) {
			for(int j = i * 2; j < 10000010; j += i)
				prime[j] = false;
		}
	}
	vector<int> v;
	for(int i = 10000010; i; i--) {
		if(prime[i] && prime[i-2] && prime[i-6] && prime[i-8]) {
			v.push_back(i);
		}
	}
	int n;
	while(cin >> n, n) {
		cout << *lower_bound(v.begin(), v.end(), n, greater<int>()) << endl;
	}
}