#include <bits/stdc++.h>
using namespace std;

using ll = long long;

int main() {
    vector<int> prime;
    vector<bool> is_prime(1e7+1, true);
    is_prime[0] = is_prime[1] = false;
    for(int i=2; i<is_prime.size(); ++i) {
        if(is_prime[i]) {
            prime.push_back(i);
            for(int j=i+i; j<is_prime.size(); j+=i) {
                is_prime[j] = false;
            }
        }
    }
    vector<int> quad;
    for(int i=3; i<prime.size(); ++i) {
        if(prime[i] == prime[i-1] + 2 && prime[i] == prime[i-2] + 6 && prime[i] == prime[i-3] + 8) {
            quad.push_back(prime[i]);
        }
    }
    int n;
    while(cin >> n, n) {
        cout << *(upper_bound(quad.begin(), quad.end(), n) - 1) << endl;
    }
}