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