#include <iostream>

bool sieve[10000001];

int main() {
	int n;

	sieve[1] = true;
	for (int i = 2; i < 10000000; ++i) {
		if (!sieve[i]) {
			for (int j = 2; i*j <= 10000000; ++j)
				sieve[i * j] = true;
		}
	}

	while (std::cin >> n) {
		if (n == 0)
			return 0;
		for (int i = n; i >= 13; --i) {
			if (!(sieve[i] || sieve[i - 2] || sieve[i - 6] || sieve[i - 8])) {
				std::cout << i << std::endl;
				break;
			}
		}
	}
	return 0;
}