#include <bits/stdc++.h>
using namespace std;
static const int MAX_N = 10000001;
int P[MAX_N];
void prime();
int main(int argc, char** argv) {
  prime();
  int n;
  while (1) {
    cin >> n;
    if (n == 0) break;
    for (int i = n; i >= 13; i--) {
      if (i % 2 == 1) {
        if (P[i] == 1 && P[i - 2] == 1 && P[i - 6] == 1 && P[i - 8] == 1) {
          cout << i << endl;
          break;
        }
      }
    }
  }
}
void prime() {
  for (int i = 0; i < MAX_N; i++) {
    P[i] = 1;
  }
  int limit;
  limit = (int)sqrt((double)MAX_N);
  for (int i = 2; i <= limit; i++) {
    if (P[i] == 1) {
      for (int j = (i << 2); j <= MAX_N; j += i) {
        P[j] = 0;
      }
    }
  }
}
