#include<iostream>
#include<algorithm>

using namespace std;

bool prime[10000001];

int main() {
	for (int i = 3; i * i <= 10000000; i += 2) {
		if (!prime[i]) {
			for (int j = i * 2; j <= 10000000; j += i) {
				prime[j] = true;
			}
		}
	}
	int n;
	while (cin >> n, n) {
		for (;;n--) {
			if (!prime[n] && !prime[n - 2] && !prime[n - 6] && !prime[n - 8] && n % 2 != 0) {
				cout << n << endl;
				break;
			}
		}
	}
	return 0;
}