#include <bits/stdc++.h>
using namespace std;
vector<bool> makePrimeTableBasedOne(int);
int main() {
  vector<int> questions;
  int q;
  while (cin >> q, q) questions.push_back(q);
  int maxQuestion = *(max_element(questions.begin(), questions.end()));
  auto primeTable = makePrimeTableBasedOne(maxQuestion);
  for (auto i = questions.begin(); i != questions.end(); ++i) {
    int question = *i;
    int deltas[] = {0, 2, 4, 2};
    bool loopEnd = false;
    int k, l, j;
    for (j = ((question % 2) ? question : question - 1); !loopEnd && j >= 7;
         j -= 2)
      for (k = 0, l = j; !loopEnd && primeTable[l]; ++k, l -= deltas[k])
        if (k == 3) {
          cout << l + 8 << endl;
          loopEnd = true;
        }
  }
  return 0;
}
vector<bool> makePrimeTableBasedOne(int max) {
  vector<bool> primeBools(max + 1, true);
  double squareMax = pow(max, (double)1 / (double)2);
  primeBools[1] = false;
  for (int i = 2; i <= squareMax; ++i) {
    if (primeBools[i]) {
      for (int j = 2; i * j < max + 1; ++j) primeBools[i * j] = false;
    }
  }
  return move(primeBools);
}
