#include <bits/stdc++.h>
using namespace std;
bool isPrime[10000001];
vector<int> res;
void calc() {
  for (int i = 5; i < 10000001 - 8; i += 2) {
    if (isPrime[i] && isPrime[i + 2] && isPrime[i + 6] && isPrime[i + 8]) {
      res.push_back(i + 8);
    }
  }
}
void eratos() {
  fill(isPrime, isPrime + 10000001, true);
  for (int i = 2; i < 10000001; i++) {
    if (!isPrime[i]) continue;
    for (int j = i + i; j < 10000001; j += i) {
      isPrime[j] = false;
    }
  }
}
int main() {
  eratos();
  calc();
  while (true) {
    int n;
    cin >> n;
    if (!n) return 0;
    for (int i = 0; i < res.size(); i++) {
      if (res[i] > n) {
        cout << res[i - 1] << endl;
        break;
      }
    }
  }
}
