#include <bits/stdc++.h>
#define REP(i, n) for(int i = 0; i < n; i++)
#define dump(x) cout << #x << " = " << (x) << endl;
using namespace std;
using ll = long long;
using P = pair<ll, ll>;

int main() {
  cin.tie(0);
  ios::sync_with_stdio(false);
  int INF = 1e7;
  vector<bool> is_prime(INF + 1, true);
  for(int p = 2; p <= INF; p++) {
    if(!is_prime[p]) continue;
    for(int k = p * 2; k <= INF; k += p)
      is_prime[k] = false;
  }
  vector<int> ans(INF + 1, 0);
  int tmp;
  for(int i = 13; i < INF + 1; i++) {
    if(is_prime[i - 8] && is_prime[i - 6] && is_prime[i - 2] && is_prime[i]) {
      tmp = i;
    }
    ans[i] = tmp;
  }
  while(1) {
    int x;
    cin >> x;
    if(x == 0) { break; }
    cout << ans[x] << endl;
  }

  return 0;
}
