#include <iostream>
#include <cstring>
using namespace std;

#define MAX_N 10000001

bool table[MAX_N];

void init() {
    memset(table, 1, sizeof(table));
    table[0] = table[1] = false;
    for (int i = 2; i < MAX_N; i++) {
        if (table[i]) {
            for (int j = i + i; j < MAX_N; j+=i) {
                table[j] = false;
            }
        }
    }
}

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