#include <bits/stdc++.h>
using namespace std;
const int INF = 1 << 30;
vector<int> eratosthenes(int n) {
  vector<int> v(n);
  for (int i = 2; i < n; i++) v[i] = i;
  for (int i = 2; i * i < n; i++)
    if (v[i])
      for (int j = i * i; j < n; j += i) v[j] = 0;
  v.erase(remove((v).begin(), (v).end(), 0), v.end());
  return v;
}
int main() {
  vector<int> prime = eratosthenes(10001000);
  int n;
  while (cin >> n, n) {
    for (int i =
             upper_bound((prime).begin(), (prime).end(), n) - prime.begin() - 1;
         prime[i] >= 13; --i) {
      int a = prime[i];
      if (prime[i - 1] == a - 2 && prime[i - 2] == a - 6 &&
          prime[i - 3] == a - 8) {
        cout << a << endl;
        break;
      }
    }
  }
}
