#include <iostream>
#include <vector>

using namespace std;

const int N = 10000000;

int main() {
  int n;
  vector<bool> is_prime(N + 1, true);
  is_prime[0] = is_prime[1] = false;
  for (int i = 2; i <= N; ++i) {
    for (int j = 2; i * j <= N; ++j) {
      is_prime[i * j] = false;
    }
  }
  while (true) {
    cin >> n;
    if (n == 0) {
      return 0;
    }
    for (int k = n; true; --k) {
      if (k % 6 == 1 and is_prime[k] and is_prime[k - 2]
          and is_prime[k - 6] and is_prime[k - 8]) {
        cout << k << endl;
        break;
      }
    }
  }
}