#include <bits/stdc++.h>
using namespace std;
inline int sq(int x) { return x * x; }
vector<int> ps;
void primeTable(int n) {
  vector<int> table(n + 1, 0);
  for (int i = 2; i <= n; i++) {
    if (!table[i]) {
      ps.push_back(i);
      if (sq(i) <= n) table[i * i] = i;
    } else {
      int j = i, step = table[i];
      while (j + step <= n) {
        if (!table[j + step]) {
          table[j + step] = step;
          break;
        } else {
          int tmp = step;
          step = table[j + step];
          table[j + tmp] = tmp;
          j += tmp;
        }
      }
    }
  }
  return;
}
inline bool isPrime(int x) {
  for (int i = 0; sq(ps[i]) < x; i++) {
    if (!(x % ps[i])) return false;
  }
  return true;
}
int main() {
  int n;
  primeTable(10000);
  while (scanf("%d", &n), n) {
    for (int i = n;; i--) {
      if (isPrime(i) && isPrime(i - 2) && isPrime(i - 6) && isPrime(i - 8)) {
        printf("%d\n", i);
        break;
      }
    }
  }
  return 0;
}
