#include <bits/stdc++.h>
using namespace std;
vector<bool> dp, searched;
bool isprime(int n, int k);
bool is_prime(int n) {
  if (searched[n]) {
    return dp[n];
  }
  return isprime(n, 2);
}
bool isprime(int n, int k) {
  if (n < k * k) {
    return searched[n] = dp[n] = true;
  }
  if (n % k == 0) {
    return searched[n] = dp[n] = true;
  }
  if (k > 2) {
    return isprime(n, k + 2);
  }
  return isprime(n, k + 1);
}
int main() {
  int N;
  dp = searched = vector<bool>(10000001, false);
  while (true) {
    cin >> N;
    if (N == 0) {
      break;
    }
    int Ans = 1145141919;
    if (N % 2 == 0) {
      N -= 1;
    }
    for (int i = N;; i -= 2) {
      if (is_prime(i - 8) && is_prime(i - 6) && is_prime(i - 2) &&
          is_prime(i)) {
        Ans = i;
        break;
      }
    }
    cout << Ans << endl;
  }
  return 0;
}
