#include <bits/stdc++.h>
using namespace std;
inline int to_int(string s) {
  int v;
  istringstream sin(s);
  sin >> v;
  return v;
}
template <class T>
inline string to_str(T x) {
  ostringstream sout;
  sout << x;
  return sout.str();
}
const int N_prime = 10000000;
class prime {
 public:
  prime();
  bool used[N_prime];
};
prime::prime() {
  memset(used, N_prime, sizeof(used));
  int lim = sqrt(N_prime);
  for (int i = 2; i < lim; i++) {
    if (used[i] == false) {
      continue;
    }
    for (int j = i * 2; j < N_prime; j += i) {
      used[j] = false;
    }
  }
}
int main() {
  prime obj;
  int n;
  while (cin >> n, n) {
    int res;
    for (int i = n; i >= 13; i--) {
      if (obj.used[i] && obj.used[i - 2]) {
        if (obj.used[i - 2] && obj.used[i - 6]) {
          if (obj.used[i - 6] && obj.used[i - 8]) {
            res = i;
            break;
          }
        }
      }
    }
    cout << res << endl;
  }
  return 0;
}
