#include<stdio.h>
#define M 10000000
char p[M]={1,1};
int main(){
  int i,j,n;
  for(i=2;i*i<M;i++){
    if(p[i])continue;
    for(j=i*i;j<M;j+=i)p[j]=1;
  }
  while(scanf("%d",&n),n){
    for(;1;n--){
      if(p[n-8]+p[n-6]+p[n-2]+p[n]==0)break;
    }
    printf("%d\n",n);