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

const int MX = 10000000;
bool p[MX];

int main() {
    memset(p, false, sizeof p);
    p[0] = p[1] = true;
    for (int i=2; i*i<MX; ++i) {
        if ( ! p[i]) {
            for (int j=i*i; 0<j && j<MX; j+=i) {
                p[j] = true;
            }
        }
    }
    int n;
    while (cin >> n, n) {
        for (int i=n; i>=0; --i) {
            if (p[i-8] + p[i-6] + p[i-2] + p[i] == 0) {
                cout << i << endl;
                break;
            }
        }
    }
    return 0;
}