#include <bits/stdc++.h>
using namespace std;
int prime(int a, int b, int c, int d) {
  for (int e = 3;; e += 2) {
    if (a % e == 0 || b % e == 0 || c % e == 0 || d % e == 0) return false;
    if ((e + 1) * (e + 1) > d) return true;
  }
}
int main() {
  while (1) {
    int a;
    cin >> a;
    if (a == 0) break;
    for (int b = a - (a % 6) + 1;; b -= 6) {
      if (prime(b, b - 2, b - 6, b - 8)) {
        cout << b << endl;
        break;
      }
    }
  }
}
