#include <bits/stdc++.h>
using namespace std;
vector<int> fourprime;
bool prime[10000005];
void Prime();
int main() {
  int n;
  Prime();
  while (1) {
    cin >> n;
    if (!n) break;
    vector<int>::iterator ans;
    ans = upper_bound(fourprime.begin(), fourprime.end(), n);
    cout << *(ans - 1) << endl;
  }
}
void Prime() {
  prime[1] = true;
  for (int i = 3; i * i <= 1000000; i += 2) {
    if (!prime[i]) {
      for (int j = i * 2; j <= 1000000; j += i) {
        prime[j] = true;
      }
    }
  }
  for (int i = 13; i <= 10000000; i += 2) {
    if (!prime[i] && !prime[i - 2] && !prime[i - 6] && !prime[i - 8]) {
      fourprime.push_back(i);
    }
  }
}
