#include <bits/stdc++.h>
using namespace std;
const int MAX_N = 10000010;
int n, quad[MAX_N];
bool sieve[MAX_N];
void solve() {
  int res;
  for (int i = 1;; i++) {
    if (quad[i] > n) {
      res = quad[i - 1];
      break;
    }
  }
  cout << res << endl;
}
int main(int argc, char const* argv[]) {
  memset(sieve, true, sizeof sieve);
  for (int i = 4; i < MAX_N; i += 2) sieve[i] = false;
  for (int i = 3; i < MAX_N; i += 2)
    if (sieve[i])
      for (int j = i + i; j < MAX_N; j += i) sieve[j] = false;
  quad[0] = 13;
  quad[1] = 19;
  int ii = 2;
  for (int i = 23; i < MAX_N; i += 2) {
    if (sieve[i - 8] && sieve[i - 6] && sieve[i - 2] && sieve[i]) {
      quad[ii] = i;
      ii++;
    }
  }
  while (cin >> n, n) {
    solve();
  }
  return 0;
}
