#include <bits/stdc++.h>
using namespace std;
static const double EPS = 1e-10;
static const double PI = acos(-1.0);
static const int mod = 10007;
static const int INF = 1 << 25;
static const long long LL_INF = 1152921504606846976;
static const int dx[] = {-1, 0, 1, 0, 1, -1, 1, -1};
static const int dy[] = {0, -1, 0, 1, 1, 1, -1, -1};
vector<int> pm;
int n;
bool is_pm[10000000] = {false};
int main() {
  bool can_add;
  for (int i = 3; i < 10000000; i += 2) {
    can_add = true;
    for (int j = 0; j < pm.size() && (pm[j]) * (pm[j]) <= i; ++j) {
      if (i % pm[j] == 0) {
        can_add = false;
        break;
      }
    }
    if (can_add) {
      pm.push_back(i);
      is_pm[i] = true;
    }
  }
  while (~scanf("%d", &n) && n) {
    if (n % 2 == 0) {
      n--;
    }
    for (int i = n; i >= 13; i -= 2) {
      if (is_pm[i] && is_pm[i - 2] && is_pm[i - 6] && is_pm[i - 8]) {
        printf("%d\n", i);
        break;
      }
    }
  }
  return 0;
}
