#include <bits/stdc++.h>
int main() {
  int* table = new int[10000500];
  int limit, p;
  int* info = new int[2000000];
  p = 0;
  for (int i = 0; i < 10000500; i++) table[i] = 1;
  table[0] = 0;
  table[1] = 0;
  limit = sqrt(10000500);
  for (int i = 2; i <= limit; i++) {
    if (table[i] == 1) {
      for (int k = 2 * i; k < 10000500; k += i) {
        table[k] = 0;
      }
    }
  }
  info[0] = 13;
  p++;
  for (int i = 17; i <= 10000499; i += 2) {
    if (table[i] == 1 && table[i - 2] == 1 && table[i - 6] == 1 &&
        table[i - 8] == 1)
      info[p++] = i;
  }
  int n;
  while (true) {
    scanf("%d", &n);
    if (n == 0) break;
    for (int i = 0; i < p; i++) {
      if (info[i] > n) {
        printf("%d\n", info[i - 1]);
        break;
      }
    }
  }
  return 0;
}
