#include <bits/stdc++.h>
using namespace std;
long long int flg[1000000], i, j, n;
int main(void) {
  while (cin >> n && n) {
    for (i = 0; i <= n; i++) flg[i] = 1;
    for (i = 2; i * i <= n; i++) {
      if (flg[i] == 1) {
        for (j = 2; j * i < n; j++) flg[i * j] = 0;
      }
    }
    for (i = n; i >= 13; i--) {
      if (flg[i] == 1) {
        if (flg[i - 2] == 1 && flg[i - 6] == 1 && flg[i - 8] == 1) {
          cout << i << endl;
          break;
        }
      }
    }
  }
}
