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