#include <bits/stdc++.h>
using namespace std;
int main() {
  int n;
  vector<int> a, box;
  for (int i = 0; i <= 10000000; i++) a.push_back(1);
  a[0] = 0;
  a[1] = 0;
  for (int i = 2; i <= 10000000; i++)
    if (a[i]) {
      if (i >= 13 &&
          (a[i] == 1 && a[i - 2] == 1 && a[i - 6] == 1 && a[i - 8] == 1)) {
        box.push_back(i);
      }
      for (int j = i * 2; j <= 10000000; j += i) a[j] = 0;
    }
  while (cin >> n, n) {
    int i;
    for (i = 0; i < (int)box.size() && box[i] <= n; i++)
      ;
    cout << box[i - 1] << endl;
  }
  return 0;
}
