#define _CRT_SECURE_NO_WARNINGS
#include "bits/stdc++.h"
using namespace std;

char * seive(int sz){
    char* isprime = (char*)malloc(sz + 1);
    fill(isprime, isprime + sz + 1, true);
    isprime[0] = isprime[1] = false;
    for (int i = 2; i*i <= sz; i++){
        if (!isprime[i]) continue;
        for (int j = i*i; j <= sz; j += i){
            isprime[j] = false;
        }
    }
    return isprime;
}

int main(int argc, char ** argv) {
    char * isprime = seive(10000000 + 100);
    for (int n; scanf("%d", &n), n != 0;){
        while (!isprime[n] || !isprime[n - 2] || !isprime[n - 6] || !isprime[n - 8]) n--;
        printf("%d\n", n);
    }
    free(isprime);
}