#include <bits/stdc++.h>
int prime[10000001];
int max4[10000001];
int main() {
  for (int i = 2; i * i <= 10000000; i++) {
    if (prime[i] == 0) {
      prime[i] = 1;
      for (int j = i * 2; j <= 10000000; j += i) prime[j] = -1;
    }
  }
  for (int i = 3162; i <= 10000000; i++)
    if (prime[i] == 0) prime[i] = 1;
  for (int i = 13; i <= 10000000; i++) {
    if (prime[i] == 1 && prime[i - 2] == 1 && prime[i - 6] == 1 &&
        prime[i - 8] == 1)
      max4[i] = i;
    else
      max4[i] = max4[i - 1];
  }
  int a;
  while (scanf("%d", &a), a) printf("%d\n", max4[a]);
}
