#include <bits/stdc++.h>
using namespace std;
bool prime[10000000];
int main() {
  long long n, ans;
  for (int i = 0; i < 10000000; i++) prime[i] = true;
  prime[0] = prime[1] = false;
  for (int i = 0; i < 5000; i++) {
    if (!prime[i]) continue;
    for (int j = i * 2; j < 10000000; j += i) {
      prime[j] = false;
    }
  }
  while (cin >> n, n) {
    for (int i = 8; i < n + 1; i++) {
      if (prime[i - 8] && prime[i - 6] && prime[i - 2] && prime[i]) ans = i;
    }
    cout << ans << endl;
  }
  return 0;
}
