#include <stdio.h>
#define MAX 10000000
/* SIZE ((MAX) + 1)*/
/*1 ñf */
/*0 fÈ¢µfóâ */
int sieve[MAX];
int four[1000];
int main()
{
  int i, j,f=0;
  int i2; /* i Ì 2 æðÛ·éÏ */
  /* 0 Æ 1 ÍfÅÍÈ¢ */
  sieve[0] = sieve[1] = 1;
  /* SIZE ÈºÌ 2 ð­ 2 Ì{ð·×Äfóâ©çO· */
  for (i = 4; i < MAX; i +=2) sieve[i] = 1;
  /* Eratostenes Ìâ¿Éæèfð©Â¯é (3©çnßé) */
  /* (i2 Í (i + 2)^2 = i^2 + 4 (i + 1) ©çvZ·é) */
  for (i = 3, i2 = 9; i2 < MAX; i2 += (i + 1) << 2, i += 2) {
    /* i ªfÈç i ð­ i Ì{ÍfÅÍÈ¢ */
    if (sieve[i] == 0) {
      /* j ÌúlÍ i^2 ©çÅæ¢ */
      for (j = i2; j < MAX; j += i + i) sieve[j] = 1;
    }
  }
  /* ÙÈé2ÂÌfÌÏÉªðÅ«éðoÍ·é */
  for (i = 3; i < MAX - 7; i += 2) {
    if (sieve[i] == 0 && sieve[i + 2] == 0 &&
	sieve[i + 6] == 0 && sieve[i + 8] == 0) {
      four[f++]=i+8;
    }
  }
  
  for(;scanf("%d",&j),j;)
    {
      for(i=0 ; ; i++){
	if(four[i] >j)
	  break;
      }
      printf("%d\n",four[i-1]);
    }
  exit(0);
  return 0;
}