#include <bits/stdc++.h>
using namespace std;
template <class T>
ostream& operator<<(ostream& os, vector<T> v) {
  for (typename vector<T>::iterator it_i = v.begin(); it_i != v.end(); ++it_i) {
    os << *it_i << ", ";
  }
  return os;
}
const int SIZE = 10000000;
bool isPrime[SIZE];
vector<int> P;
int main() {
  P.clear();
  fill(isPrime, isPrime, false);
  for (int i = 3; i < SIZE; i += 2) {
    isPrime[i] = true;
  }
  P.push_back(2);
  for (int i = 3; i < SIZE; i += 2) {
    if (!isPrime[i]) continue;
    P.push_back(i);
    for (int j = i + i; j < SIZE; j += i) {
      isPrime[j] = false;
    }
  }
  reverse(P.begin(), P.end());
  int n;
  while (cin >> n && n) {
    for (vector<int>::iterator it_i = P.begin(); it_i != P.end(); ++it_i) {
      int p = *it_i;
      if (p > n) continue;
      if (isPrime[p - 2] && isPrime[p - 6] && isPrime[p - 8]) {
        cout << p << endl;
        break;
      }
    }
  }
  return 0;
}
