#include <bits/stdc++.h>
int p[10000000 + 1], pq[1000];
int main() {
  int n, i, j;
  p[0] = p[1] = 1;
  for (i = 2; i <= 10000000 / 2; ++i)
    if (p[i] == 0)
      for (j = i + i; j <= 10000000; j += i) p[j] = 1;
  j = 0;
  for (i = 0; i < 1000; ++i) pq[i] = 10000000;
  for (i = 0; i <= 10000000; ++i)
    if (p[i] == 0 && p[i + 2] == 0 && p[i + 6] == 0 && p[i + 8] == 0) {
      pq[j] = i + 8;
      j++;
    }
  while (scanf("%d", &n) && n) {
    for (i = 999; i >= 0; i--) {
      if (pq[i] <= n) {
        printf("%d\n", pq[i]);
        break;
      }
    }
  }
  return 0;
}
