#include<iostream>
#include<vector>
using namespace std;

#define pb push_back
#define sz size()
#define clr clear()

vector<bool> pt;

void MakeTable(int n){
  pt.clr;
  pt.pb(false);pt.pb(false);pt.pb(true);
  
  while((int)pt.sz<=n+1){
    pt.pb(true);
    pt.pb(false);
  }
  
  int i = 3;
  while(i*i<=n){
    for(int j=3*i;j<=n;j+=2*i)pt[j]=false;
    do{i+=2;}while(!pt[i]);
  }
}

int main(){
  int i,n;
  MakeTable(10000000);

  for(;;){
    cin >> n;
    if(!n)break;

    for(i=n;i>=0;i--){
      if(pt[i] && pt[i-2] && pt[i-6] && pt[i-8])break;
    }

    cout << i << endl;
  }
}