#include <bits/stdc++.h>
using namespace std;
bool x[10000001];
vector<int> a;
int main() {
  for (int i = 3; i < 10000000; i += 2) {
    for (int j = 3; j <= sqrt(i); j += 2) {
      if (i % j == 0) {
        goto F;
      }
    }
    x[i] = true;
  F:;
  }
  for (int i = 0; i < 9999993; i++) {
    if (x[i] == 1 && x[i + 2] == 1 && x[i + 6] == 1 && x[i + 8] == 1) {
      a.push_back(i + 8);
    }
  }
  int n, maxn = 0;
  while (true) {
    maxn = 0;
    cin >> n;
    if (n == 0) {
      break;
    }
    for (int i = 0; i < a.size(); i++) {
      if (a[i] <= n) {
        maxn = a[i];
      }
    }
    cout << maxn << endl;
  }
}
