#include <bits/stdc++.h>
using namespace std;
int isP[10000000 + 1];
int ans[10000000 + 1];
void make_table() {
  for (int i = 0; i <= 10000000; i++) isP[i] = true;
  isP[0] = isP[1] = false;
  for (int i = 2; i * i <= 10000000; i++) {
    if (isP[i] == false) continue;
    for (int j = i * i; j <= 10000000; j += i) isP[j] = false;
  }
  ans[13] = 13;
  for (int i = 14; i <= 10000000; i++) {
    ans[i] = ans[i - 1];
    if (isP[i] && isP[i - 2] && isP[i - 6] && isP[i - 8]) ans[i] = i;
  }
}
int main() {
  make_table();
  int n;
  while (cin >> n && n) cout << ans[n] << endl;
  return 0;
}
