#include <bits/stdc++.h>
int F(int x) {
  for (int i = 3; i * i <= x; i += 2)
    if (x % i == 0) return 0;
  return 1;
}
int main() {
  int n;
  while (scanf("%d", &n), n) {
    while (n % 6 - 1) --n;
    int f[4] = {F(n - 8), F(n - 6), F(n - 2), F(n)};
    for (;;) {
      if (f[0] + f[1] + f[2] + f[3] > 3) break;
      n -= 6;
      f[3] = f[1];
      f[2] = f[0];
      f[1] = F(n - 6);
      f[0] = F(n - 8);
    }
    printf("%d\n", n);
  }
  return 0;
}
