#include <bits/stdc++.h>
using namespace std;
template <typename T>
struct RepIterator {
  T i;
  RepIterator() : i(0) {}
  RepIterator(T n) : i(n) {}
  bool operator==(const RepIterator<T>& rhs) { return i == rhs.i; }
  bool operator!=(const RepIterator<T>& rhs) { return i != rhs.i; }
  T operator*() { return i; }
  RepIterator<T> operator++() {
    i++;
    return *this;
  };
};
template <typename T>
struct RepLoop {
  T i;
  RepLoop(T n) : i(n) {}
  RepIterator<T> begin() { return RepIterator<T>(); }
  RepIterator<T> end() { return RepIterator<T>(i); }
};
template <typename T>
struct rep_range {
  static T range(T v) { return v; }
};
template <>
struct rep_range<int> {
  static RepLoop<int> range(int n) { return RepLoop<int>(n); }
};
;
template <>
struct rep_range<size_t> {
  static RepLoop<size_t> range(size_t n) { return RepLoop<size_t>(n); }
};
;
long long gcd(long long a, long long b) {
  while (b) {
    long long tmp = a % b;
    a = b;
    b = tmp;
  }
  return a;
}
long long lcm(long long a, long long b) { return a / gcd(a, b) * b; }
bool is_prime(long long n) {
  switch (n) {
    case 0:
    case 1:
      return false;
    case 2:
      return true;
  }
  if (n % 2 == 0) return false;
  for (long long i = 3; i * i <= n; i += 2)
    if (n % i == 0) return false;
  return true;
}
bool primetable[1000001];
int main() {
  int N;
  for (auto i = 2; i < 1000001; i++) primetable[i] = true;
  for (auto i = 2; i < 1000001; i++) {
    if (primetable[i]) {
      for (auto j = i * 2; j < 1000001; j += i) {
        if (j % i == 0) primetable[j] = false;
      }
    }
  }
  while (cin >> N && N) {
    for (auto i = N + 1 - 1; i >= 13; i--) {
      if (primetable[i - 8] && primetable[i - 6] && primetable[i - 2] &&
          primetable[i]) {
        cout << i << endl;
        break;
      }
    }
  }
}
