#include<bits/stdc++.h>
using namespace std;
vector<int> fourprime;
bool prime[10000005];
void Prime();
int main(){
  int n;
  Prime();
  //cout<<fourprime.size()<<endl;
  while(1){
    cin>>n;
    if(!n)break;
    vector<int>::iterator ans;
    ans=upper_bound(fourprime.begin(),fourprime.end(),n);
    cout<<*(ans-1)<<endl;
  }
}
void Prime(){
  for(int i=2;i<=10000000;i++){
    prime[i]=false;
  }
  prime[0]=prime[1]=true;
  for(int i=2;i*i<=10000000;i++){
    if(!prime[i]){
      for(int j=i*2;j<=10000000;j+=i){
	prime[j]=true;
      }
    }
  }
  for(int i=13;i<=10000000;i+=2){
    if(!prime[i]&&!prime[i-2]&&!prime[i-6]&&!prime[i-8]){
      fourprime.push_back(i);
    }
  }
}
  