#include <bits/stdc++.h>
using namespace std;
int main() {
  const int N = 10000000;
  vector<int> isp(N + 1, 1);
  isp[0] = isp[1] = 0;
  for (int i = int(0); i < int(N + 1); i++)
    if (isp[i])
      for (int j = i + i; j <= N; j += i) isp[j] = 0;
  vector<int> ps;
  for (int i = int(0); i < int(N + 1); i++)
    if (isp[i]) ps.push_back(i);
  for (int n; cin >> n, n;) {
    int res = 0;
    for (int i = 3; ps[i] <= n; i++)
      if (ps[i] - ps[i - 3] == 8) res = ps[i];
    cout << res << endl;
  }
  return 0;
}
