#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
bool prime[10000001];

int main(){
  //GgXelXÌâ¿Åf©Ç¤©Ì\ðì¬
  //f == 1, NOTf == 0
  memset(prime, 1, sizeof(prime));
  prime[0] = prime[1] = 0;
  for(int i = 2 ; i <= 10000000 ; i++){
    if(prime[i]){
      for(int j = i*2 ; j <= 10000000 ; j += i){
	prime[j] = 0;
      }
    }
  }
  
  int n;
  
  while(cin >> n && n){
    int i = n;
    while(!(prime[i] && prime[i-2] && prime[i-6] && prime[i-8])) i--;
    cout << i << endl;
  }
  return 0;
}