#include <iostream>
using namespace std;
const int N_MAX = 10000000;
bool isNotPrime[N_MAX + 1];
int main () {
	for (int i = 2; i * i < N_MAX; ++i) {
		if (!isNotPrime[i]) {
			for (int j = i << 1; j < N_MAX; j += i) {
				isNotPrime[j] = true;
			}
		}
	}
	int n;
	while (cin >> n, n) {
		for (; n > 13; n--) {
			if (!(isNotPrime[n] || isNotPrime[n - 2] || isNotPrime[n - 6] || isNotPrime[n - 8])) break;
		}
		cout << n << endl;
	}
	return 0;
}