#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
#include <complex>
#include <cstring>
#include <cstdlib>
#include <string>
#include <cmath>
#include <queue>
using namespace std;

#define REP(i,n) for(int i=0;i<(int)n;++i)
#define FOR(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();++i)
#define ALL(c) (c).begin(), (c).end()
const int INF = 1<<30;

#define N 10000000

int main() {
  vector<bool> p(N,1);
  p[0]=p[1]=0;
  REP(i,N) if (p[i])
    for(int j=i*2;j<N;j+=i)
      p[j] = 0;
  int n;
  while(cin>>n,n) {
    for (int i=n; i>=0; --i) {
      if (p[i]&&p[i-2]&&p[i-6]&&p[i-8]) {
        cout << i << endl;
        break;
      }
    }
  }
}