#include <bits/stdc++.h>
using namespace std;
bool prime[10000001];
int main() {
    for(long long int i=3;i<3162;i++)if(!prime[i])for(long long int j=i*2;j<10000001;j+=i)prime[j]=1;
    int n;
    while(cin>>n,n){
        if(n%2==0)n--;
        for(;;n-=2){
            if(!prime[n]&&!prime[n-2]&&!prime[n-6]&&!prime[n-8]){
                cout<<n<<endl;
                break;
            }
        }
    }
}