#include <bits/stdc++.h>
using namespace std;
const int INF = 2 << 28;
const double EPS = 1e-10;
map<int, int> p;
int isPrime(int N) {
  if (p[N]) return p[N];
  if (!(N % 2)) return p[N] = -1;
  for (int i = 3; i * i <= N; i += 2) {
    if (!(N % i)) {
      return p[N] = -1;
    }
  }
  return p[N] = 1;
}
int main() {
  int n;
  while (cin >> n, n) {
    for (int i = n - !(n % 2); i >= 13; i -= 2) {
      if (~isPrime(i) && ~isPrime(i - 2) && ~isPrime(i - 6) &&
          ~isPrime(i - 8)) {
        cout << i << endl;
        break;
      }
    }
  }
}
