#include <iostream>
#include <vector>

using namespace std;

#define MAX_N 10000000

bool sosuu[MAX_N+1];
int main() {
//	vector<int> s;

	fill(&sosuu[0], &sosuu[MAX_N], true);
	sosuu[0] = sosuu[1] = false;

	for (int i = 2; i < MAX_N+1; ++i)
		if (sosuu[i]) {
//			s.push_back(i);
			for (int j = i*2; j < MAX_N+1; j += i)
				sosuu[j] = false;
		}

	int n;
	while (cin >> n, n) {
		for (int i = n; i >= 13; --i)
			if (sosuu[i] && sosuu[i-2] && sosuu[i-6] && sosuu[i-8]) {
				cout << i << endl;
				break;
			}
	}
}