#include <bits/stdc++.h>
using namespace std;
int main(void) {
  long long int flg[10000000], i, j, n;
  for (i = 3; i <= 10000000; i++) flg[i] = 1;
  for (i = 2; i * i <= 10000000; i++) {
    if (flg[i] == 1) {
      for (j = 2; j * i < 10000000; j++) flg[i * j] = 0;
    }
  }
  while (cin >> n && n) {
    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;
        }
      }
    }
  }
}
