#include <bits/stdc++.h>
using namespace std;
vector<int> p;
bool check(int n) {
  for (int i = 0; i < p.size(); i++) {
    if (p[i] == n)
      return true;
    else if (n % p[i] == 0)
      return false;
    else if (p[i] * p[i] > n)
      return true;
  }
  return true;
}
int main() {
  int N;
  p.push_back(2);
  for (int i = 3; i <= 10000; i++) {
    for (int j = 0; j < p.size(); j++) {
      if (i % p[j] == 0) break;
      if (p[j] * p[j] > i) {
        p.push_back(i);
        break;
      }
    }
  }
  while (cin >> N && N != 0) {
    int maxim = 0;
    for (int i = 13; i <= N; i += 6)
      if (check(i) && check(i - 2) && check(i - 6) && check(i - 8)) maxim = i;
    cout << maxim << endl;
  }
  return 0;
}
