#include <iostream>
using namespace std;

bool prime[10000001];

void init_prime() {
    fill(prime, prime+10000001, true);
    prime[0] = prime[1] = false;
    for (int i = 3; i <= 3163; i += 2) {
        if (prime[i]) {
            for (int d = i * 2, j = i + d; j <= 10000000; j += d) {
                prime[j] = false;
            }
        }
    }
}

int main() {
    int n, x;
    
    init_prime();

    while (cin >> n, n) {
        for (int i = n - 1 + (n&1); i >= 13; i -= 2) {
            if (prime[i] && prime[i-2] && prime[i-6] && prime[i-8]) {
                cout << i << endl;
                break;
            }
        }
    }
    return 0;
}