#include <bits/stdc++.h>
using namespace std;
int main() {
  vector<int> primes;
  primes.push_back(2);
  for (int i = (3); i < (999999); i++) {
    bool flg = true;
    for (int j = 0; primes[j] * primes[j] <= i; j++) {
      if (i % primes[j] == 0) {
        flg = false;
        break;
      }
    }
    if (flg) primes.push_back(i);
  }
  int d[] = {8, 6, 2, 0};
  while (true) {
    int n;
    cin >> n;
    if (n == 0) break;
    int p = upper_bound((primes).begin(), (primes).end(), n) - primes.begin();
    for (int i = p + 1 - 1; i >= 0; i--) {
      if (primes[i] > n) continue;
      if (i >= 3) {
        if (primes[i] == (primes[i - 1] + d[2]) &&
            primes[i] == (primes[i - 2] + d[1]) &&
            primes[i] == (primes[i - 3] + d[0])) {
          cout << primes[i] << endl;
          break;
        }
      }
    }
  }
  return 0;
}
