#include <bits/stdc++.h>
int check(long s);
int main() {
  long n, i;
  while (scanf("%d", &n) != 0) {
    if (n == 0) break;
    for (i = n; i >= 13; i--) {
      if (check(i) == 0 && check(i - 2) == 0 && check(i - 6) == 0 &&
          check(i - 8) == 0) {
        printf("%d\n", i);
        break;
      }
    }
  }
  return 0;
}
int check(long s) {
  long i, f;
  for (i = 2, f = 0; i < s / 2 + 1; i++) {
    if ((s / i) * i == s) return -1;
  }
  return 0;
}
