#include <bits/stdc++.h>
using namespace std;
const long long MAX_N = 1000010;
int main() {
  cin.tie(0);
  ios::sync_with_stdio(false);
  bool prime[MAX_N];
  for (long long i = 2; i <= MAX_N; ++i) {
    prime[i] = true;
  }
  for (long long i = 2; i <= MAX_N; ++i) {
    for (long long j = 2; i * j <= MAX_N; ++j) {
      prime[i * j] = false;
    }
  }
  int n;
  while (cin >> n && n) {
    for (int i = n; i >= 13; --i) {
      if (prime[i] && prime[i - 2] && prime[i - 6] && prime[i - 8]) {
        cout << i << endl;
        break;
      }
    }
  }
  return 0;
}
