#include <bits/stdc++.h>
using namespace std;
int main() {
  bool *prime = (bool *)malloc(sizeof(bool) * 10000000);
  for (int i = 0; i < 10000000; i++) {
    prime[i] = 1;
  }
  prime[0] = prime[1] = 0;
  for (int i = 0; i * i < 10000000; i++) {
    if (prime[i] == 1) {
      for (int j = i * 2; j < 10000000; j = j + i) {
        prime[j] = 0;
      }
    }
  }
  int *primelist = (int *)malloc(sizeof(int) * 10000000);
  int j = 0;
  for (int i = 0; i < 10000000; i++) {
    if (prime[i] == 1) {
      primelist[j] = i;
      j++;
      if (j > 10000000 - 1) {
        break;
      }
    }
  }
  int n;
  while (cin >> n, n) {
    int ans = 0;
    int s;
    int num = 10000000 - 1;
    for (int i = num; i > 0; i--) {
      if (primelist[i] > n) {
      } else {
        if ((primelist[i] - primelist[i - 1] == 2) &&
            (primelist[i - 2] - primelist[i - 3] == 2) &&
            (primelist[i - 1] - primelist[i - 2] == 4)) {
          ans = primelist[i];
          break;
        }
      }
    }
    cout << ans << endl;
  }
  return 0;
}
