#include <bits/stdc++.h>
int p[10000000];
int main(void) {
  int i, j, x;
  p[0] = 1;
  for (i = 2; i <= 10000000 / 2; i++) {
    for (j = 2; i * j <= 10000000; j++) {
      if (p[i * j - 1] == 0) p[i * j - 1] = 1;
    }
  }
  for (i = 0; i < 10000000; i++) {
    if (p[i] == 0) {
      if (p[i + 2] != 0 || p[i + 6] != 0 || p[i + 8] != 0) p[i] = 1;
    }
  }
  for (; scanf("%d", &j), j;) {
    for (i = 0; i + 9 <= j; i++) {
      if (p[i] == 0) {
        x = i + 9;
      }
    }
    printf("%d\n", x);
  }
  return 0;
}
