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