#include <bits/stdc++.h>
int prime[10000001];
int main(void) {
  int result[1000], s = 0;
  while (1) {
    int n;
    scanf("%d", &n);
    if (n == 0) {
      break;
    }
    double sqr = sqrt((double)n);
    for (int i = 2; i <= n; i++) {
      prime[i] = 0;
    }
    int front, back = 2, value[100000], suffix = 0;
    while (1) {
      for (int i = back; i <= n; i++) {
        if (prime[i] == 0) {
          front = i;
          value[suffix++] = front;
          break;
        }
      }
      if (front >= sqr) {
        break;
      }
      for (int i = front; i <= n; i += front) {
        prime[i] = 1;
      }
    }
    for (int i = front + 1; i <= n; i++) {
      if (prime[i] == 0) {
        prime[i] = 1;
        value[suffix++] = i;
      }
    }
    bool success = false;
    for (int i = suffix - 1; i >= 0; i--) {
      if (value[i] - value[i - 1] == 2) {
        if (value[i] - value[i - 2] == 6) {
          if (value[i] - value[i - 3] == 8) {
            result[s++] = value[i];
            break;
          }
        }
      }
    }
  }
  for (int i = 0; i < s; i++) {
    printf("%d\n", result[i]);
  }
  return 0;
}
