#include<iostream>
using namespace std;
#define rep(i,a) for(int i = 0 ; i < a ; i ++)
#define loop(i,a,b) for(int i = a ; i < b ; i ++)
const int M = (1e7);
bool p[M];
void isPrime(){
  rep(i,M)p[i] = true;
  p[0] = p[1] = false;
  loop(i,2,M){
    if(p[i])
      for(int j = i + i ; j < M ; j += i)
	p[j] = false;
  }
}
int main(void){
  isPrime();
  int Q[4] = {-8,-6,-2,0};
  int n;
  while(cin>>n,n){
    if(n%2==0)n--;
    for(int i = n ; ; i -=2){
      bool find = true;
      rep(j,4)if(!p[i+Q[j]])find = false;
      if(find){
	cout<<i<<endl;
	break;
      }
    }
  }
}