#include <bits/stdc++.h>
int p[10000000];
int four[1000];
int main(void) {
  int i, j, f = 0;
  for (i = 2; i <= 10000000 / 2; i++) {
    for (j = 2; i * j <= 10000000; j++) {
      if (p[i * j] == 0) p[i * j] = 1;
    }
  }
  for (i = 3; i < 10000000 - 7; i += 2) {
    if (p[i] == 0 && p[i + 2] == 0 && p[i + 6] == 0 && p[i + 8] == 0) {
      four[f++] = i + 8;
    }
  }
  for (; scanf("%d", &j), j;) {
    for (i = 0; four[i] <= j; i++)
      ;
    printf("%d\n", four[i - 1]);
  }
  return 0;
}
