#include <bits/stdc++.h>
using namespace std;
int prime[1000001];
void make(void);
int main() {
  make();
  while (1) {
    int n;
    cin >> n;
    if (n == 0) break;
    if (n > 1000000) n = 1000000;
    for (int i = n; i >= 13; i--) {
      if (prime[i] == 1 && prime[i - 2] == 1 && prime[i - 6] == 1 &&
          prime[i - 8] == 1) {
        cout << i << endl;
        break;
      }
    }
  }
  return 0;
}
void make(void) {
  for (int i = 0; i <= 1000000; i++) prime[i] = 1;
  prime[0] == 0;
  prime[1] == 0;
  for (int i = 2; i * i <= 1000000; i++) {
    if (prime[i] == 1) {
      for (int j = i * 2; j <= 1000000; j += i) prime[j] = 0;
    }
  }
}
