#include <bits/stdc++.h>
bool isprime(int n) {
  for (int i = 2; i * i <= n; ++i)
    if (n % i == 0) return false;
  return n != 1;
}
int main() {
  int n;
  while (std::cin >> n, n) {
    int a[4];
    int p = 0;
    while (true) {
      while (!isprime(n)) --n;
      if (!p || a[p - 1] - n == (p == 2 ? 4 : 2))
        a[p++] = n--;
      else
        p = 0, a[p++] = n--;
      if (p == 4) break;
    }
    std::cout << a[0] << std::endl;
  }
  return 0;
}
