#include <bits/stdc++.h>
using namespace std;
static bool isprime[10000001];
void MakePrime() {
  for (long long int i = 0; i < 10000001; ++i) {
    isprime[i] = true;
  }
  isprime[0] = isprime[1] = false;
  for (long long int i = 2; i < 10000001; ++i) {
    if (isprime[i]) {
      for (long long int j = 2; i * j < 10000001; ++j) {
        isprime[i * j] = false;
      }
    }
  }
}
int main() {
  set<int> S;
  MakePrime();
  for (int i = 2; i < 10000001 - 8; ++i) {
    if (isprime[i] && isprime[i + 2] && isprime[i + 6] && isprime[i + 8]) {
      S.insert(i + 8);
    }
  }
  vector<int> v;
  for (set<int>::iterator its = S.begin(); its != S.end(); ++its) {
    v.push_back(*its);
  }
  while (true) {
    int n;
    int ans;
    cin >> n;
    if (n == 0) break;
    int L = 0;
    int R = v.size();
    int preM = -1;
    while (true) {
      int M = (L + R) / 2;
      if (M == preM) break;
      if (v[M] > n) {
        R = M;
      } else if (v[M] < n) {
        ans = max(ans, v[M]);
        L = M;
      } else {
        ans = n;
        break;
      }
      preM = M;
    }
    cout << ans << endl;
  }
  return 0;
}
