#include <iostream>
using namespace std;

#define MAX 10000001
bool prime[MAX]={};
int yo[MAX]={};
int main(){

  prime[1] = true; prime[2] = false;
  for(int i=3;i<MAX;i++){
    if(!prime[i])
      for(int j=2;i*j<MAX;j++){
	prime[i*j] = true;
      }
  }
  
  for(int i=13;i<MAX;i++){
    if(!prime[i-8] && !prime[i-6] && !prime[i-2] && !prime[i]){
      yo[i] = i; 
    }
    else
      yo[i] = yo[i-1];
  }
  int n;
  while(1){
    cin >> n;
    if(n == 0) break;
    cout << yo[n] <<"\n";
  }  
}