#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

//const int MAX_N = 100001;
const int MAX_N = 10000001;

bool prime[MAX_N];
int main(){
    cin.tie(0);
    ios::sync_with_stdio(false);

    for(int i = 2; i <= MAX_N; ++i){
        prime[i] = true;
    }

    for(int i = 2; i <= MAX_N; ++i){
        if(!prime[i]) continue;
        for(int j = 2; i * j <= MAX_N; ++j){
            prime[i * j] = false;
        }
    }

    int n;
    while(cin >> n && n){
        for(int i = n; i >= 13; --i){
            if(prime[i] && prime[i - 2] && prime[i - 6] && prime[i - 8]){
                cout << i << endl;
                break;
            }
        }
    }

    return 0;
}