#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int, int>;

const int MAXN = 10000010;
bool is_p[MAXN];
vector<int> p, fp;

void sieve() {
  fill_n((bool*)is_p, MAXN, true);
  is_p[0] = is_p[1] = false;
  for (int i = 2; i < MAXN; i++) {
    if (!is_p[i]) continue;
    p.emplace_back(i);
    for (int j = 2 * i; j < MAXN; j += i) {
      is_p[j] = false;
    }
  }
}

int main() {
  cin.tie(0);
  ios_base::sync_with_stdio(false);
  cout << fixed << setprecision(10);
  
  sieve();
  for (int i = 0; i + 3 < int(p.size()); i++) {
    if (p[i + 1] != p[i] + 2) continue;
    if (p[i + 2] != p[i] + 6) continue;
    if (p[i + 3] != p[i] + 8) continue;
    fp.emplace_back(p[i + 3]);
  }
  int n;
  while (cin >> n, n) {
    cout << *(upper_bound(fp.begin(), fp.end(), n) - 1) << endl; 
  }

  return 0;
}
