#include<iostream>
using namespace std;
bool a[10000001];
int main() {
	fill(a, a + 10000001, true);
	a[0] = false; a[1] = false;
	for (int i = 3; i <= 10000000; i += 2) {
		if (a[i]) {
			int j = 2;
			while (i*j <= 10000000) {
				a[i*j] = false;
				j++;
			}
		}
	}
	int n;
	while (cin >> n&&n != 0) {
		int b = 13;
		for (int i = n; i >= 13; i--) {
			if (a[i] && a[i - 2] && a[i - 6] && a[i - 8]) {
				b = i;
				break;
			}
		}
		cout << b << endl;
	}
}