#include <bits/stdc++.h>
using namespace std;
const int dx[4] = {0, 1, 0, -1};
const int dy[4] = {1, 0, -1, 0};
vector<int> prime;
bool isprime[20000010];
vector<int> Quadruplet;
void sieve() {
  for (int i = 0; i <= 20000010; i++) isprime[i] = true;
  isprime[0] = isprime[1] = false;
  int Size = 0;
  for (int i = 2; i < 20000010; i++) {
    if (isprime[i]) {
      Size++;
      for (int j = 2 * i; j < 20000010; j += i) isprime[j] = false;
    }
  }
  for (int i = 0; i < Size; i++) {
    if (i + 8 <= 20000010 && isprime[i] && isprime[i + 2] && isprime[i + 6] &&
        isprime[i + 8]) {
      Quadruplet.push_back(i + 8);
    }
  }
}
int main() {
  clock_t start, end;
  sieve();
  int n;
  while (cin >> n && n) {
    cout << (upper_bound(Quadruplet.begin(), Quadruplet.end(), n)[-1]) << endl;
  }
  return 0;
}
