#include <bits/stdc++.h>
int primes[10000001], a;
int main() {
  int xss, i, j, x;
  while (scanf("%d", &x), x) {
    for (i = 2; i <= x; i++) {
      if (primes[i] == 1) continue;
      for (j = i * i; j <= x; j += i) primes[j] = 1;
      if (i >= 8 && primes[i - 2] == 0 && primes[i - 6] == 0 &&
          primes[i - 8] == 0)
        a = i;
    }
    printf("%d\n", a);
  }
  return 0;
}
