#include <iostream>
#include <algorithm>
#include<vector>

using namespace std;

class Solver{};

int main() {
	vector<bool> is_prime(10000005, true);
	vector<int> primes;
	for (int i = 2; i < is_prime.size(); i++) {
		if (!is_prime[i])continue;

		primes.emplace_back(i);
		for (int j = 2; i * j < is_prime.size(); j++) {
			is_prime[i * j] = false;
		}
	}

	vector<int> vals;
	for (int i = 3; i < primes.size(); i++) {
		if (primes[i - 1] == primes[i] - 2
			&& primes[i - 2] == primes[i] - 6
			&& primes[i - 3] == primes[i] - 8) {
			vals.emplace_back(primes[i]);
		}
	}

	while (true) {
		int n;
		cin >> n;
		if (n == 0)break;

		int bottom = 0;
		int top = vals.size();
		while (bottom + 1 < top) {
			int mid = (bottom + top) / 2;
			if (vals[mid] <= n)bottom = mid;
			else top = mid;
		}

		cout << vals[bottom] << endl;
	}
}
