#include <bits/stdc++.h>
using namespace std;
const int UPTO = 10000000;
const int USUM = sqrt(UPTO);
int main() {
  vector<bool> sos(UPTO + 1, true);
  sos[0] = sos[1] = false;
  for (int i = 2; i <= USUM; i++) {
    if (sos[i]) {
      for (int j = i * 2; j <= UPTO; j += i) {
        sos[j] = false;
      }
    }
  }
  int n;
  for (;;) {
    scanf("%d", &n);
    if (n == 0) break;
    int yo = 1, last = 2, max = -1;
    for (int i = 13; i <= n; i++) {
      if (sos[i]) {
        if (sos[i - 2] && sos[i - 6] && sos[i - 8]) {
          max = i;
        }
      }
    }
    printf("%d\n", max);
  }
}
