#include <bits/stdc++.h>
using namespace std;
bool prime[1000000001];
int main() {
  for (int i = 3; i * i <= 1000000000; i += 2) {
    if (!prime[i]) {
      for (int j = i * 2; j <= 1000000000; j += i) {
        prime[j] = true;
      }
    }
  }
  int n;
  while (cin >> n, n) {
    for (;; n--) {
      if (!prime[n] && !prime[n - 2] && !prime[n - 6] && !prime[n - 8] &&
          n % 2 != 0) {
        cout << n << endl;
        break;
      }
    }
  }
  return 0;
}
