#include <bits/stdc++.h>
using namespace std;
bool IsPrime(int n) {
  static vector<int> notPrime;
  static vector<int> Prime;
  if (n < 2)
    return false;
  else if (n == 2)
    return true;
  if (n % 2 == 0) return false;
  if (find(notPrime.begin(), notPrime.end(), n) != notPrime.end()) return false;
  if (find(Prime.begin(), Prime.end(), n) != Prime.end()) return true;
  for (int i = 3; i * i <= n; i += 2) {
    if (n % i == 0) {
      notPrime.push_back(n);
      return false;
    }
  }
  Prime.push_back(n);
  return true;
}
int retqp(int n) {
  if (n % 2 == 0) n--;
  while (!(IsPrime(n - 8) && IsPrime(n - 6) && IsPrime(n - 2) && IsPrime(n)))
    n -= 2;
  return n;
}
int main(void) {
  while (true) {
    int n;
    scanf("%d", &n);
    if (n == 0) break;
    printf("%d\n", retqp(n));
  }
  return 0;
}
