#include <bits/stdc++.h>

using namespace std;

typedef long long ll;
typedef vector<int> vi;
typedef pair<int,int> pii;
#define REP(i,n) for(int i=0;i<(n);i++)
#define ALL(v) (v).begin(),(v).end()
#define DEBUG(x) cout<<(#x)<<":"<<x<<endl

const int SIEVE_MAX = 12525252;

int main(){
  vector<bool> sieve(SIEVE_MAX,true);
  vector<int> ans(SIEVE_MAX,0);
  sieve[0] = sieve[1] = false;
  REP(i,SIEVE_MAX){
    if(!sieve[i]){
      if(i>0)ans[i]=ans[i-1];
      continue;
    }
    int x=i<<1;
    while(x<SIEVE_MAX){
      sieve[x]=false;
      x+=i;
    }
    if(i>=9 && sieve[i-2] && sieve[i-6] && sieve[i-8]){
      ans[i] = i;
    }else{
      ans[i] = ans[i-1];
    }
  }
  while(true){
    int x;
    scanf("%d",&x);
    if(x==0)break;
    printf("%d\n",ans[x]);
  }
  return 0;
}