#include <iostream>

using namespace std;

const int max_p = 10000000;
bool prime[max_p + 1];

void init_prime()
{
    for (int i = 0; i <= max_p; i++)
        prime[i] = true;
    prime[0] = prime[1] = false;

    for (int i = 2; i * i < max_p; i++)
        if (prime[i])
            for (int j = 2 * i; j <= max_p; j += i)
                prime[j] = false;
}

int main()
{
    int n;

    init_prime();

    while (cin >> n, n) {
        while (true) {
            if (prime[n] && prime[n - 2] && prime[n - 6] && prime[n - 8]) {
                cout << n << endl;
                break;
            }
            n--;
        }
    }

    return 0;
}