#include <cstdio>
#include <algorithm>
using namespace std;
static const int MAX_N = 10000001;
bool primes[MAX_N];
int qr[900];

int main() {
    fill(primes, primes+MAX_N, 1);
    fill(qr, qr+13, 0);
    primes[0] = primes[1] = false;
    for (int i = 2; i * i < MAX_N; i++) {
        if (!primes[i]) continue;
        for (int j = i * i; j < MAX_N; j+=i) primes[j] &= 0;
    }
    qr[0] = 0;
    int idx = 1;
    for (int i = 2; i < MAX_N-8; i++)
        if (primes[i] && primes[i+2] && primes[i+6] && primes[i+8]) qr[idx++] = i+8;
    int n, res;

    for (; ;) {
        scanf("%d", &n);
        if (n == 0) break;
        res = int(upper_bound(qr, qr+idx, n)-qr-1);
        printf("%d\n", qr[res]);
    }
    return 0;
}

