#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;

int main() {

    constexpr ll nlimit = 10000000LL;
    vector<bool> is_prime(nlimit + 1, true);
    is_prime[0] = is_prime[1] = false;
    for (ll i = 2; i <= nlimit; i++) {
        if (!is_prime[i]) continue;
        for (ll j = i * 2; j <= nlimit; j += i) {
            is_prime[j] = false;
        }
    }

    vector<ll> yotsugo = {13}; yotsugo.reserve(100000);
    for (ll i = 19; i <= nlimit; i += 10) {
        if (is_prime[i] && is_prime[i-2] && is_prime[i-6] && is_prime[i-8]) {
            yotsugo.push_back(i);
        }
    }
    
    ll n;
    while (cin >> n, n) {

        auto ub = --upper_bound(yotsugo.begin(), yotsugo.end(), n);

        cout << *ub << endl;

    }

}
