#include <bits/stdc++.h>
using namespace std;
bool f(int n) {
  for (int i = 3; i < n / 2; i += 2) {
    if (n / i == 0) return false;
  }
  return true;
}
int main() {
  int a;
  while (true) {
    cin >> a;
    if (a == 0) return 0;
    if (a % 2 == 0) a--;
    while (!(f(a) && f(a - 2) && f(a - 6) && f(a - 8))) {
      a -= 2;
    }
    cout << a << endl;
  }
}
