#include<vector>
#include<list>
#include<algorithm>
#include<iostream>
#include<string>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
using namespace std;
int main(){
  int i,j,k,l;
  int n,p[900];
  p[0]=13;
  j=1;
  for(i=19;i<10000000;i+=10){
    l=(int)sqrt(i)+1;
    for(k=3;k<l;k+=2){
      if(i%k==0||
	 (i-2)%k==0||
	 (i-6)%k==0||
	 (i-8)%k==0)
	break;
    }
    if(k>=l){
      p[j]=i;
      j++;
    }
  }
  while(cin>>n&&n){
    for(i=j-1;p[i]>n;i--);
    cout<<p[i]<<endl;
  }
  return 0;
}