#include <bits/stdc++.h>
using namespace std;
const int SIZE = 10000000;
bool isprime[SIZE + 1];
vector<int> prime;
void make_prime() {
  for (int i = 2; i <= SIZE; i++) {
    isprime[i] = true;
  }
  isprime[0] = false;
  isprime[1] = false;
  for (int i = 2; i <= SIZE; i++) {
    if (isprime[i] == false) continue;
    for (int j = i * 2; j <= SIZE; j += i) {
      isprime[j] = false;
    }
    prime.push_back(i);
  }
}
vector<int> yotugo;
void make_list() {
  for (int i = 0; i <= (prime.size() - 4); i++) {
    if (prime[i + 1] == (prime[i] + 2) && prime[i + 2] == (prime[i] + 6) &&
        prime[i + 3] == (prime[i] + 8)) {
      yotugo.push_back(prime[i + 3]);
    }
  }
}
int check(int n) {
  int i;
  for (i = 0; yotugo[i] <= n; i++)
    ;
  return yotugo[i - 1];
}
int main() {
  make_prime();
  make_list();
  int n;
  while (cin >> n) {
    if (n == 0) break;
    cout << check(n) << endl;
  }
  return 0;
}
