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