#include<iostream>
#include<vector>
#include<sstream>
#include<algorithm>
using namespace std;
#define REP(i,b,n) for(int i=b;i<n;i++)
#define rep(i,n)   REP(i,0,n)
#define pb         push_back

const int N = 10000001;

class f{
public:
  int a,b,c,d;
};

bool a[N];
bool b[N];
vector<int> pr;
//99982249
void generate(){
  for(int i=0;i<N;i+=2)a[i]=false,b[i]=false;
  for(int i=1;i<N;i+=2)a[i]=true,b[i]=false;
  a[1]=false;
  for(int i=3;i*i <= N;i+=2){
    if (a[i])for(int j=2*i;j<N;j+=i)a[j]=false;
  }
  
  for(int i=3;i+8 < N;i+=2){
    if (a[i] && a[i+2]&&a[i+6] && a[i+8]){
      b[i+8]=true;
    }
  }
  for(int i=3;i<N;i+=2)if (b[i])pr.pb(i);
}

int main(){
  generate();
  int n;
  while(cin>>n && n){
    int ans ;
    rep(i,pr.size()){
      if (pr[i] > n)break;
      ans=pr[i];
    }
    cout <<  ans << endl;
  }
}