#include <bits/stdc++.h>
using namespace std;
bool prime[5000000];
int main() {
  for (int i = 0; i < 5000000; i++) prime[i] = true;
  for (int i = 3; i * i < 10000000; i += 2)
    for (int j = i / 2 + i; j < 5000000; j += i) prime[j] = false;
  int n;
  while (true) {
    cin >> n;
    if (n == 0) break;
    n /= 2;
    while (true) {
      if (prime[n] && prime[n - 1] && prime[n - 3] && prime[n - 4]) break;
      n--;
    }
    cout << n * 2 + 1 << endl;
  }
  return 0;
}
