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


vector<int> sieve(int n) {
	vector<int> res(1, 2);
	vector<bool> prime(n, true);
	for(int i = 3; i < n; i += 2) {
		if(prime[i]) {
			res.push_back(i);
			for(int j = i * 3; j < n; j += i * 2)
				prime[j] = false;
		}
	}

	return res;
}

int main() {
	cin.tie(0);
	ios::sync_with_stdio(false);

	vector<int> prime = sieve(10000000), q;

	for(int i = 3; i < prime.size(); ++i) {
		if(prime[i - 3] + 8 == prime[i])
			if(prime[i - 3] + 6 == prime[i - 1])
				if(prime[i - 3] + 2 == prime[i - 2])
					q.push_back(prime[i]);
	}

	for(int n; cin >> n, n;) {
		int idx = upper_bound(q.begin(), q.end(), n) - q.begin();
		cout << q[idx - 1] << endl;
	}
	
	return EXIT_SUCCESS;
}