#include<cstdio>
#include<vector>
#include<algorithm>
const int size = 10000005;
bool sosu[size] = {false};
using namespace std;
int main(){
  vector<int> vec;
  for(int i=3;i<size;i+=2){
    if(!sosu[i]){
      if(i>=13 && !sosu[i] && !sosu[i-2] && !sosu[i-6] && !sosu[i-8]) vec.push_back(i);
      if((long long)i*i < size){
	for(int j=i*i;j<size;j+=i) sosu[j] = true;
      }
    }
  }
  int n;
  while(scanf("%d",&n),n!=0){
    printf("%d\n",*(upper_bound(vec.begin(),vec.end(),n)-1));
  }
  return(0);
}

