#include <bits/stdc++.h>
using namespace std;
int prime[500];
int main() {
  int cnt = 0, d = 2;
  while (true) {
    bool isprime = true;
    for (int i = 0; i < cnt; i++)
      if (d % prime[i] == 0) isprime = false;
    if (isprime) {
      prime[cnt] = d, cnt++;
    }
    d++;
    if (d * d > 10000000) break;
  }
  int n, a[4];
  while (true) {
    cin >> n;
    if (n == 0) break;
    if (n % 2 == 0) n--;
    while (true) {
      a[0] = n, a[1] = n - 2, a[2] = n - 6, a[3] = n - 8;
      bool ok = true;
      for (int i = 0; i < 4; i++)
        for (int j = 0; j < cnt; j++)
          if (a[i] % prime[j] == 0 && a[i] != prime[j]) ok = false;
      if (ok) break;
      n -= 2;
    }
    cout << n << endl;
  }
  return 0;
}
