#include <bits/stdc++.h>
using namespace std;
bool is_prime(int n) {
  for (int p = 2; p * p <= n; ++p) {
    if (n % p == 0) {
      return false;
    }
  }
  return true;
}
int main() {
  int n;
  while (true) {
    cin >> n;
    if (n == 0) {
      return 0;
    }
    for (int k = n; true; --k) {
      if (is_prime(k) and is_prime(k - 2) and is_prime(k - 6) and
          is_prime(k - 8)) {
        cout << k << endl;
        break;
      }
    }
  }
}
