#include <bits/stdc++.h>
int sosu(int);
int n, OZA;
int main(void) {
  int i;
  while (1) {
    OZA = 0;
    scanf("%d", &n);
    if (n == 0) break;
    for (i = n; i >= 8; i--) {
      if (sosu(i) == 1 && sosu(i - 2) == 1 && sosu(i - 6) == 1 &&
          sosu(i - 8) == 1) {
        OZA = i;
        break;
      }
    }
    printf("%d\n", OZA);
  }
  return 0;
}
int sosu(int x) {
  int i;
  if (x < 2)
    return 0;
  else if (x == 2)
    return 1;
  if (x % 2 == 0) return 0;
  for (i = 3; i * i <= x; i += 2) {
    if (x % i == 0) return 0;
  }
  return 1;
}
