#include <bits/stdc++.h>
int e[10000000 + 1] = {1, 1, 0};
int r[10000000 + 1] = {0};
int main(int argc, char* argv[]) {
  int i, j;
  for (j = 2; j < 10000000; ++j) {
    if (e[j]) continue;
    for (i = j * 2; i <= 10000000; i += j) {
      e[i] = 1;
    }
  }
  for (i = 8; i <= 10000000; ++i) {
    r[i] = !(e[i - 8] || e[i - 6] || e[i - 2] || e[i]);
  }
  for (i = 13; i <= 10000000; ++i) {
    if (r[i]) {
      r[i] = i;
    } else {
      r[i] = r[i - 1];
    }
  }
  for (;;) {
    int n;
    scanf("%d", &n);
    if (!(n)) break;
    printf("%d\n", r[n]);
  }
  return (0);
}
