#include <bits/stdc++.h>
using namespace std;
const int Max = 10000000;
int main(void) {
  bool prime[Max];
  int in, i;
  for (int i = 0; i < Max; i++) prime[i] = true;
  prime[1] = false;
  for (int i = 2; i < Max; i++) {
    if (prime[i]) {
      for (int s = i * 2; s <= Max; s += i) prime[s] = false;
    }
  }
  while (1) {
    cin >> in;
    if (in == 0) break;
    for (i = in; i > 0; i--) {
      if (prime[i] == true && prime[i - 2] == true && prime[i - 4] == true &&
          prime[i - 8]) {
        cout << i << "\n";
        break;
      }
    }
  }
  return 0;
}
