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