#include <bits/stdc++.h>
int prmt[10000005] = {};
int rest[10000005] = {};
int main(void) {
  int n, i, j;
  prmt[0] = -1;
  prmt[1] = -1;
  for (i = 2; i <= 10000000; i++) {
    if (prmt[i] == -1) continue;
    prmt[i] = 1;
    j = i * 2;
    while (j <= 10000000) {
      prmt[j] = -1;
      j += i;
    }
  }
  j = 13;
  for (i = 13; i <= 10000000; i++) {
    if (prmt[i] == 1 && prmt[i - 2] == 1 && prmt[i - 6] == 1 &&
        prmt[i - 8] == 1)
      j = i;
    rest[i] = j;
  }
  while (1) {
    scanf("%d", &n);
    if (n == 0) break;
    printf("%d\n", rest[n]);
  }
  return 0;
}
