#include <bits/stdc++.h>
using namespace std;
bool prime3200[3200];
void eratos3200() {
  prime3200[0] = false;
  prime3200[1] = false;
  for (int i = 2; i < 3200; i++) prime3200[i] = true;
  for (int i = 2; i < 3200; i++) {
    if (!prime3200[i]) continue;
    for (int j = i + i; j < 3200; j += i) prime3200[j] = false;
    if (3200 < i * i) return;
  }
}
bool prime(int n) {
  if (n <= 1) return false;
  if (n < 3200) return prime3200[n];
  if (n % 2 == 0) return false;
  for (int i = 3; i * i <= n; i += 2) {
    if (!prime3200[i]) continue;
    if (n % i == 0) return false;
  }
  return true;
}
int main() {
  eratos3200();
  while (true) {
    int n;
    cin >> n;
    if (n == 0) break;
    for (int i = n; i >= 13; i--)
      if (prime(i) && prime(i - 2) && prime(i - 6) && prime(i - 8)) {
        cout << i << endl;
        break;
      }
  }
  return 0;
}
