#define MAX 10000005
int p[MAX];
int four[1000];

int main(void)
{
  int i,j,f=0;

  for(i=2;i<MAX;i++)
    if(~p[i])
      for(j=i*2;j<MAX;j+=i)
	p[j]=1;
  
  for(i=3 ; i < MAX-7 ; i+=2){
    if(p[i] == 0 && p[i+2]==0 && p[i+6]==0 && p[i+8]==0)
      {
	four[f++]=i+8;
      }
    four[f]=10000005;
  }
  
  for(;scanf("%d",&j);)
    {
      if(j==0)
	exit(0);
      for(i=0 ;four[i]<=j; i++);
      printf("%d\n",four[i-1]);
    }
  
  return 0;
}