#include <bits/stdc++.h>
using namespace std;
bool isp[10000000] = {};
void makeEra() {
  for (int i = 2; i <= 10000; i++) {
    if (isp[i]) {
      for (int j = 2; i * j <= 10000000; j++) {
        isp[i * j] = false;
      }
    }
  }
}
int main() {
  for (long long i = 0; i < (long long)(1000000); i++) isp[i] = true;
  isp[0] = isp[1] = false;
  makeEra();
  int n;
  while (cin >> n) {
    if (n == 0) break;
    for (int i = n;; i--) {
      if (isp[i] && isp[i - 2] && isp[i - 6] && isp[i - 8]) {
        cout << i << endl;
        break;
      }
    }
  }
}
