#include <bits/stdc++.h>
using namespace std;
const double EPS = 1e-9;
template <class T>
T RoundOff(T a) {
  return int(a + .5 - (a < 0));
}
template <class T, class C>
void chmax(T& a, C b) {
  if (a < b) a = b;
}
template <class T, class C>
void chmin(T& a, C b) {
  if (b < a) a = b;
}
template <class T, class C>
pair<T, C> mp(T a, C b) {
  return make_pair(a, b);
}
bool isPrime(int x) {
  if (x == 2) return true;
  if (x % 2 == 0 || x < 2) return false;
  for (int i = 3; i * i <= x; i += 2) {
    if (x % i == 0) {
      return false;
    }
  }
  return true;
}
int main() {
  int n;
  while (cin >> n && n) {
    vector<int> table(5, 2);
    int dx[] = {0, 2, 6, 8};
    if (n % 2 == 0) n--;
    for (int i = n - 8; 0 <= i; i -= 2) {
      for (int j = 0; j < 4; j++) {
        int prv = j + (1 < j);
        if (!(table[prv] == 1 ||
              (table[prv] == 2 && (table[prv] = isPrime(i + dx[j])))))
          break;
        else if (j == 3) {
          cout << i + 8 << endl;
          goto ng;
        }
      }
      rotate(table.begin(), table.end() - 1, table.end());
      table[0] = 2;
    }
  ng:;
  }
}
