#include <bits/stdc++.h>
using namespace std;
int main() {
  bool p[10000001] = {};
  p[0] = p[1] = 1;
  for (int i = (2); (i) < (1001); (i)++) {
    if (!p[i]) {
      for (int j = i * i; j <= 10000000; j += i) {
        p[j] = 1;
      }
    }
  }
  int n;
  while (cin >> n, n) {
    for (int i = n; i >= 13; i--) {
      if (!p[i] && !p[i - 2] && !p[i - 6] && !p[i - 8]) {
        cout << i << endl;
        break;
      }
    }
  }
}
