#include <bits/stdc++.h>
int main(void) {
  long i, j, n;
  char prime[10000002] = {0};
  for (i = 2; i < 10000000; i++) prime[i] = 1;
  for (i = 2; i <= 10000000; i++)
    if (prime[i])
      for (j = i + i; j <= 10000000; j += i) prime[j] = 0;
  while (scanf("%ld", &n), n) {
    n = n % 2 ? n : n - 1;
    for (i = n; i > 8; i -= 2)
      if (prime[i] + prime[i - 2] + prime[i - 6] + prime[i - 8] == 4) break;
    printf("%ld\n", i);
  }
  return 0;
}
