#include <iostream>
#include <vector>

using namespace std;

int main() {
	vector<int> furui(10000001, 0);
	furui[0] = furui[1] = 1;
	for (int i = 2; i*i < 10000001; i++) {
		if (furui[i] == 0) {
			for (int j = 2; j <= 10000000/i; j++) {
				furui[i*j] = 1;
			}
		}
	}
	long long int n;
	while (cin >> n) {
		if (n == 0) {
			break;
		}
		for (int i = n; i >= 0; i--) {
			if (furui[i] == 0) {
				if (furui[i-2] == 0) {
					if (furui[i-6] == 0) {
						if (furui[i-8] == 0) {
							cout << i << endl;
							break;
						} else {
							i -= 8;
						}
					} else {
						i -= 6;
					}
				} else {
					i -= 2;
				}
			}
		}
	}
	return 0;
}