#include <bits/stdc++.h>
char f[10000000];
int getprime(int a[], int s) {
  int i, j, c = 0;
  for (i = 2; i <= s; i++) {
    if (!f[i]) {
      a[c++] = i;
      for (j = i + i; j <= s; j += i) {
        f[j] = 1;
      }
    }
  }
  return c;
}
int cmp(const void* p, const void* q) {
  int a = *(const int*)p;
  int b = *(const int*)q;
  return a == b ? 0 : a > b ? 1 : -1;
}
int main(void) {
  int n, a[664580], c, q, r, s;
  c = getprime(a, 10000000);
  for (;;) {
    scanf("%d", &n);
    if (!n) break;
    q = n - 2;
    r = n - 6;
    s = n - 8;
    while (!bsearch(&n, a, c, sizeof(int), cmp) ||
           !bsearch(&q, a, c, sizeof(int), cmp) ||
           !bsearch(&r, a, c, sizeof(int), cmp) ||
           !bsearch(&s, a, c, sizeof(int), cmp)) {
      n--;
      q = n - 2;
      r = n - 6;
      s = n - 8;
    }
    printf("%d\n", n);
  }
  return 0;
}
