#include <bits/stdc++.h>
using namespace std;
long long prime[10000001];
void Eratosthenes(int n) {
  for (int i = 0; i < n; i++) prime[i] = true;
  prime[1] = false;
  for (int i = 2; i < (int)sqrt(n); i++) {
    if (prime[i]) {
      for (int j = 0; i * (j + 2) < n; j++) {
        prime[i * (j + 2)] = 0;
      }
    }
  }
}
int main() {
  Eratosthenes(10000001);
  int n;
  while (cin >> n && n) {
    long long ans = 0;
    for (int i = n; i >= 0; i--) {
      if (prime[i] && prime[i - 2] && prime[i - 6] && prime[i - 8]) {
        ans = i;
        break;
      }
    }
    cout << ans << endl;
  }
}
