#include <bits/stdc++.h>
int main() {
  std::vector<int> prime, quad;
  prime.push_back(2);
  for (int i = 3; i <= 10000000; i += 2) {
    bool f = true;
    for (int j = 0; j < prime.size() && prime[j] * prime[j] <= i; j++) {
      if (i % prime[j] == 0) {
        f = false;
        break;
      }
    }
    if (f) {
      int p_size = prime.size();
      if (p_size >= 3 && prime[p_size - 3] == i - 8 &&
          prime[p_size - 2] == i - 6 && prime[p_size - 1] == i - 2) {
        quad.push_back(i);
      }
      prime.push_back(i);
    }
  }
  int n;
  while (std::cin >> n, n) {
    for (int i = quad.size() - 1; i >= 0; i--) {
      if (quad[i] <= n) {
        std::cout << quad[i] << std::endl;
        break;
      }
    }
  }
}
