#include <bits/stdc++.h>
using namespace std;
const double EPS = 1e-8;
const int MAX = 10000000;
bool is_prime[MAX + 1];
int quad[MAX + 1];
int main() {
  fill(is_prime, is_prime + MAX + 1, true);
  for (int i = 2, until = (int)sqrt((double)MAX) + 1; i <= until; ++i) {
    if (is_prime[i]) {
      for (int j = 2 * i; j <= MAX; j += i) is_prime[j] = false;
    }
  }
  int q = -1;
  for (int i = 13; i <= MAX; ++i) {
    if (is_prime[i] && is_prime[i - 2] && is_prime[i - 6] && is_prime[i - 8])
      q = i;
    quad[i] = q;
  }
  int n;
  while (scanf("%d", &n), n) printf("%d\n", quad[n]);
  return 0;
}
