#include <bits/stdc++.h>
int p(int x) {
  int y = 3, z = 9;
  for (; z <= x && x % y; y += 2) z += y - ~y;
  return z > x;
}
int main(void) {
  int n;
  for (; scanf("%d", &n), n;)
    for (n = n - 1 | 1; n;)
      n = p(n) && p(n - 2) && p(n - 6) && p(n - 8) ? !printf("%d\n", n) : n - 2;
  return 0;
}
