#include <bits/stdc++.h>
using namespace std;
int is_prime[10000001];
int prime[10000001];
int main() {
  memset(is_prime, 1, sizeof(is_prime));
  is_prime[0] = is_prime[1] = false;
  int p = 0;
  for (int i = 2; i <= 10000001; i++) {
    if (is_prime[i]) {
      prime[p++] = i;
      for (int j = i * 2; j <= 10000001; j += i) is_prime[j] = false;
    }
  }
  int i;
  while (scanf("%d", &i), i) {
    int j = lower_bound(prime, prime + p, i) - prime;
    for (int ans = j;; ans--) {
      if (prime[ans] <= i && prime[ans] - prime[ans - 3] == 8) {
        printf("%d\n", prime[ans]);
        break;
      }
    }
  }
  return 0;
}
