#include <bits/stdc++.h>
using namespace std;
static const double EPS = 1e-5;
int so[10000001];
int main() {
  so[0] = so[1] = 1;
  for (int i = 2; i * i <= 10000000; i++) {
    if (so[i] == 1) continue;
    for (int j = i; j * i <= 10000000; j++) {
      so[j * i] = 1;
    }
  }
  int n;
  while (cin >> n) {
    if (n == 0) break;
    while (1) {
      if (so[n] | so[n - 2] | so[n - 6] | so[n - 8])
        ;
      else
        break;
      --n;
    }
    cout << n << endl;
  }
  return 0;
}
