#include <bits/stdc++.h>
int sosu(int);
int main(void) {
  int i1, i2, i3, yo[3], max, cnt;
  scanf("%d", &i1);
  while (i1 != 0) {
    max = 0;
    if (i1 % 2 == 0) i1--;
    for (i2 = i1; i2 >= 13; i2 -= 2) {
      cnt = sosu(i2);
      if (cnt == 1) {
        yo[0] = i2 - 2;
        yo[1] = i2 - 6;
        yo[2] = i2 - 8;
        for (i3 = 0; i3 <= 2; i3++) cnt += sosu(yo[i3]);
        if (cnt == 4 && max < i2) {
          max = i2;
          break;
        }
      }
    }
    printf("%d\n", max);
    scanf("%d", &i1);
  }
  return 0;
}
int sosu(int s1) {
  int s2, s3 = 2;
  float temp;
  temp = (float)s1;
  s2 = (int)sqrt(temp);
  while (s1 % s3 != 0 && s2 != s3) s3++;
  if (s2 == s3 && s1 % s3 != 0)
    return 1;
  else
    return 0;
}
