#include <bits/stdc++.h>
using namespace std;
bool p[10000000];
void erato() {
  fill(p, p + 10000000, true);
  p[0] = p[1] = false;
  for (int i = 0; i < 10000000; i++) {
    if (!p[i]) continue;
    for (int j = i + i; j < 10000000; j += i) {
      p[j] = false;
    }
  }
}
int main() {
  erato();
  int n;
  while (cin >> n, n) {
    for (int i = n;; i--) {
      if (p[i] && p[i - 2] && p[i - 6] && p[i - 8]) {
        cout << n << endl;
        break;
      }
    }
  }
}
