#include<iostream>

using namespace std;

char prime[9973220];

void make(void);

int main(){
  make();
  while(1){
    int n;
    cin >> n;
    if(n == 0) break;

    if(n >= 9973220) n = 9973219;
    
    for(int i = n; i >= 13; i--){
      if(prime[i] == 1 && prime[i-2] == 1 && prime[i-6] == 1 && prime[i-8] ==1){
	cout << i << endl;
	break;
      }
    }
  }
  return 0;
}

void make(void){
  for(int i = 0; i < 9973220; i++) prime[i] = 1;

  prime[0] == 0;
  prime[1] == 0;

  for(int i = 2; i*i < 9973220; i++){
    if(prime[i] == 1){
      for(int j = i*2; j < 9973220; j+=i) prime[j] = 0;
    }
  }
}