#include <bits/stdc++.h>
using namespace std;
long long prime[10000011];
bool is_prime[10000011];
long long MAX[10000011];
void sieve(long long n) {
  long long p = 0;
  for (long long i = 0; i < n + 1; i++) is_prime[i] = true;
  is_prime[0] = is_prime[1] = false;
  for (long long i = 2; i < n + 1; i++) {
    if (is_prime[i]) {
      prime[p++] = i;
      for (long long j = i * 2; j <= n; j += i) {
        is_prime[j] = false;
      }
    }
  }
}
signed main() {
  long long n;
  sieve(10000001);
  MAX[9] = 0;
  for (long long i = 10; i < 10000001; i++) {
    MAX[i] = MAX[i - 1];
    if (is_prime[i] && is_prime[i - 2] && is_prime[i - 6] && is_prime[i - 8]) {
      MAX[i] = i;
    }
  }
  while (cin >> n && n) {
    cout << MAX[n] << endl;
  }
}
