#include <bits/stdc++.h>
using namespace std;
void MakePrimeArray(deque<bool>& A, int n) {
  A[0] = A[1] = false;
  for (int i = 2; i < n; i++) {
    A[i] = true;
  }
  for (int i = 2; i * i < n; i++) {
    if (A[i]) {
      for (int j = i * i; j < n; j += i) {
        A[j] = false;
      }
    }
  }
}
void yotuko(deque<int>& A) {
  deque<int>::iterator it = A.begin();
  for (int i = 0; i < A.size() - 3; i++) {
    if ((*(it + 1) == ((*it) + 2) && (*(it + 2)) == (*it + 6)) &&
        (*(it + 3) == (*it + 8)))
      A.erase(it);
    else
      it++;
  }
}
int main() {
  int n = 10000001;
  deque<bool> primearray;
  primearray.resize(n);
  MakePrimeArray(primearray, n);
  while (true) {
    int innum;
    cin >> innum;
    if (innum == 0) break;
    int answer = 0;
    int a = 0;
    int it = 0;
    if (innum > 19) {
      a = innum;
      a -= 11;
      it = a / 30;
      while ((!(primearray[(it * 30) + 11])) ||
             (!(primearray[(it * 30) + 11 + 2])) ||
             (!(primearray[(it * 30) + 11 + 6])) ||
             (!(primearray[(it * 30) + 11 + 8]))) {
        it--;
      }
      answer = it * 30 + 11 + 8;
    } else {
      answer = 13;
    }
    cout << answer << endl;
  }
  return 0;
}
