#include <bits/stdc++.h>
int n;
std::vector<bool> pr(10000001, true);
std::set<int> sets;
int main() {
  for (int i = 2; i <= 10000000; ++i) {
    if (pr[i]) {
      for (long long j = ((long long)i) * i; j <= 10000000ll; j += i) {
        pr[j] = false;
      }
      if (i >= 13) {
        if (pr[i - 2] && pr[i - 6] && pr[i - 8]) {
          sets.insert(i);
        }
      }
    }
  }
  while (std::cin >> n, n) {
    auto it = sets.upper_bound(n);
    --it;
    std::cout << *it << std::endl;
  }
}
