#include <bits/stdc++.h>
using namespace std;
int main() {
  const int N = 10000000;
  deque<bool> isp(N + 1, true);
  isp[0] = isp[1] = false;
  for (int i = int(0); i < int(N + 1); i++)
    if (isp[i])
      for (int j = i + i; j <= N; j += i) isp[j] = false;
  for (int n; cin >> n, n;) {
    for (int i = n;; i--)
      if (isp[i] && isp[i - 2] && isp[i - 6] && isp[i - 6]) {
        cout << i << endl;
        break;
      }
  }
  return 0;
}
