#include <bits/stdc++.h>
int sieve[((10000000) + 1)];
int four[10000000];
int main() {
  int i, j, f = 0;
  int i2;
  for (i = 0; i < ((10000000) + 1); i++) sieve[i] = 1;
  sieve[0] = sieve[1] = 0;
  for (i = 4; i < ((10000000) + 1); i += 2) sieve[i] = 0;
  for (i = 3, i2 = 9; i2 < ((10000000) + 1); i2 += (i + 1) << 2, i += 2) {
    if (sieve[i] == 1) {
      for (j = i2; j < ((10000000) + 1); j += i + i) sieve[j] = 0;
    }
  }
  for (i = 3; i < ((10000000) + 1) - 8; i += 2) {
    if (sieve[i] == 1 && sieve[i + 2] == 1 && sieve[i + 6] == 1 &&
        sieve[i + 8] == 1) {
      four[f++] = i + 8;
    }
  }
  for (; scanf("%d", &j), j;) {
    for (i = 0;; i++) {
      if (four[i] > j) break;
    }
    printf("%d\n", four[i - 1]);
  }
  return 0;
}
