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

vector<int> prime;
vector<int> ls;

void sieve(int N){
    prime.resize(N+1,1);
    prime[0] = prime[1] = 0;
    for(int i=2;i*i<=N;i+=i%2+1){
        for(int j=i*i;j<=N;j+=i){
            prime[j] = 0;
        }
    }
    for(int i=2;i<=N;i++){
        if(prime[i])ls.push_back(i);
    }
}

int main() {
    sieve(int(1e7+100));
    int n;
    while(cin >> n, n){
        int ans;
        for(int i=0;ls[i]<=n-8;i++){
            if(ls[i+1]-ls[i]==2 && ls[i+2]-ls[i]==6 && ls[i+3]-ls[i]==8){
                ans = ls[i+3];
            }
        }
        cout << ans << endl;
    }
    return 0;
}
