#include <bits/stdc++.h>
using namespace std;
vector<int> pr;
vector<int> Qpr;
bool isp[11451419];
void eratos(int mx) {
  for (int i = 0; i <= mx; i++) isp[i] = true;
  isp[0] = false;
  isp[1] = false;
  for (int i = 2; i <= mx; i++) {
    if (isp[i]) {
      pr.push_back(i);
      for (int j = 2 * i; j <= mx; j += i) isp[j] = false;
    }
  }
  return;
}
int main() {
  eratos(11451400);
  int n;
  while (cin >> n, n) {
    for (int i = 3; i < pr.size(); i++) {
      int a = pr[i - 3];
      int b = pr[i - 2];
      int c = pr[i - 1];
      int d = pr[i];
      if (b - a == 2 && c - b == 4 && d - c == 2) Qpr.push_back(d);
    }
    int ans = 0;
    for (int i = 0; i < Qpr.size(); i++) {
      if (Qpr[i] > n) break;
      ans = Qpr[i];
    }
    cout << ans << endl;
  }
  return 0;
}
