#include <bits/stdc++.h>
using namespace std;
vector<int> prime;
void sieve(int n) {
  vector<bool> is_prime(n, 1);
  prime.push_back(1);
  for (int i = 2; i <= n; i++) {
    if (is_prime[i] == false) continue;
    prime.push_back(i);
    for (int j = i; j <= n; j += i) is_prime[j] = false;
  }
}
int main(int argc, char *argv[]) {
  sieve((int)1e7 + 100);
  int n;
  while (std::cin >> n, n) {
    int start = upper_bound(prime.begin(), prime.end(), n) - prime.begin();
    start--;
    for (int i = start; i >= 0; i--) {
      int a = prime[i];
      if (prime[i - 1] == a - 2 && prime[i - 2] == a - 6 &&
          prime[i - 3] == a - 8) {
        std::cout << prime[i] << std::endl;
        break;
      }
    }
  }
  return 0;
}
