#include <bits/stdc++.h>
using namespace std;
int prime(int a) {
  if (a % 2 == 0) return false;
  if (a % 3 == 0) return false;
  for (int b = 5; b < a; b += 2) {
    if (a % b == 0) return false;
    if ((b + 1) * (b + 1) > a) 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) && prime(b - 2) && prime(b - 6) && prime(b - 8)) {
        cout << b << endl;
        break;
      }
    }
  }
}
