#include <bits/stdc++.h>
using namespace std;
bool prime[10000010];
void eratos() {
  for (int i = 0; i < 10000010; i++) prime[i] = false;
  for (int i = 3; i < 10000010; i += 2) prime[i] = true;
  prime[2] = true;
  int lim = (int)sqrt((double)10000010) + 1;
  for (int i = 3; i <= lim; i += 2) {
    if (!prime[i]) continue;
    for (int j = i + i; j < 10000010; j += i) prime[j] = false;
  }
}
int main() {
  int size;
  map<int, int> maxi;
  eratos();
  for (int i = 13; i < 10000010; i++) {
    if (prime[i] && prime[i - 2] && prime[i - 6] && prime[i - 8]) maxi[i] = i;
  }
  while (true) {
    cin >> size;
    if (size == 0) break;
    for (int i = size; i >= 12; i--) {
      if (maxi[i] != 0) {
        cout << i << endl;
        break;
      }
    }
  }
  return 0;
}
