#include <bits/stdc++.h>
using namespace std;
int p[10000000];
int four[1000];
void check() {
  int i, j;
  for (i = 2; i <= 10000000 / 2; i++) {
    if (p[i] == 0) {
      for (j = 2; i * j <= 10000000; j++) {
        p[i * j] = 1;
      }
    }
  }
}
int main(void) {
  int i, j, f = 0;
  check();
  for (i = 3; i < 10000000 - 7; i += 2) {
    if (p[i] == 0 && p[i + 2] == 0 && p[i + 6] == 0 && p[i + 8] == 0) {
      four[f++] = i + 8;
    }
  }
  for (; cin >> j, j;) {
    for (i = 0; four[i] <= j; i++)
      ;
    cout << four[i - 1] << endl;
  }
  return 0;
}
