#include<bits/stdc++.h>

using namespace std;

bool PrimeNumber[10000001];
int Ans[10000001];


void solve() {
	memset(PrimeNumber, true, sizeof(PrimeNumber));
	PrimeNumber[0] = PrimeNumber[1] = false;

	for (int i = 2; i*i < 10000001; ++i) {
		if (!PrimeNumber[i]) {
			continue;
		}
		for (int j = i*i; j < 10000001; j+=i) {
			PrimeNumber[j] = false;
		}
	}

	Ans[13] = 13;
	for (int i = 14; i < 10000001; ++i) {
		Ans[i] = Ans[i - 1];
		if (PrimeNumber[i] && PrimeNumber[i - 2] && PrimeNumber[i - 6] && PrimeNumber[i - 8]) {
			Ans[i] = i;
		}
	}
}

int main() {
	int n;

	solve();
	while (cin >> n, n) {
		cout << Ans[n] << endl;
	}

	return 0;
}
