#include <bits/stdc++.h>
using namespace std;
bool era[10000001] = {false};
void makeERA() {
  for (int i = 2; i < 1000001; i++) {
    if (era[i] != true) continue;
    for (int j = 2;; j++) {
      if (i * j <= 1000000)
        era[i * j] = false;
      else
        break;
    }
  }
  era[2] = true;
}
int main() {
  for (int i = 0; i < 10000001; i++) era[i] = true;
  era[0] = false;
  era[1] = false;
  makeERA();
  int n;
  while (cin >> n) {
    if (n == 0) break;
    if (n % 2 == 0) n--;
    for (int i = n; i >= 8; i -= 2) {
      if (era[i - 8]) {
        if (era[i - 6]) {
          if (!era[i - 4]) {
            if (era[i - 2]) {
              if (era[i]) {
                cout << i << endl;
                goto next;
              } else
                i -= 4;
            } else
              i -= 4;
          } else
            i -= 4;
        }
      } else
        i -= 2;
    }
  next:;
  }
  return 0;
}
