#include <bits/stdc++.h>
using namespace std;
const int dx[] = {1, 0, -1, 0}, dy[] = {0, 1, 0, -1};
bool us[1000010] = {false};
int p[1000010] = {0};
int main() {
  p[0] = 2;
  for (int i = 0; i <= 1000010; i += 2) {
    us[i] = true;
  }
  int cnt = 1;
  for (int i = 3; i <= 1000010; i += 2) {
    int q = 0;
    if (us[i] == true)
      continue;
    else if (us[i] == false) {
      p[cnt] = i;
      ++cnt;
      us[i] = true;
      q = i;
      for (int j = q + q; j <= 1000010; j += q) {
        us[j] = true;
      }
    }
  }
  int n;
  while (scanf("%d", &n), n) {
    int ans = 0;
    for (int i = 3; p[i] < n + 1; i++) {
      if (p[i] - 2 == p[i - 1] && p[i] - 6 == p[i - 2] && p[i] - 8 == p[i - 3])
        ans = p[i];
    }
    printf("%d\n", ans);
  }
  return 0;
}
