#include <bits/stdc++.h>
using namespace std;
int F[11451419];
bool prime(int p) {
  if (F[p] == 0) return false;
  if (F[p] == 1) return true;
  for (int i = 2; i * i <= p; i++) {
    if (F[i] == 0) continue;
    if (p % i == 0) {
      F[p] = 0;
      return false;
    }
  }
  F[p] = 1;
  return true;
}
int main() {
  for (int i = 1; i <= 10000000; i++) F[i] = -1;
  while (true) {
    int N;
    scanf("%d", &N);
    if (N == 0) break;
    if (N >= 13 && N <= 18) {
      printf("13\n");
      continue;
    }
    while (true) {
      if (N % 10 != 9) {
        N--;
        continue;
      }
      if (prime(N) && prime(N - 2) && prime(N - 6) && prime(N - 8)) {
        printf("%d\n", N);
        break;
      } else
        N -= 10;
    }
  }
  return 0;
}
