#include <bits/stdc++.h>
using namespace std;
int main() {
  int n, count = 0;
  int temp = 0;
  int maxn = 0;
  int s[10000] = {0};
  cin >> n;
  while (n != 0) {
    for (int i = 2; i <= n; i++) {
      for (int l = 2; l < i; l++) {
        if (i % l == 0) count++;
      }
      if (count == 0) {
        s[temp] = i;
        temp++;
      }
      count = 0;
    }
    for (int i = temp; i >= 0; i--) {
      if (s[i] == s[i - 1] + 2 && s[i] == s[i - 2] + 6 &&
          s[i] == s[i - 3] + 8) {
        if (s[i] > maxn) maxn = s[i];
        if (maxn != 0) break;
      }
    }
    cout << maxn << endl;
    maxn = 0;
    cin >> n;
  }
  return 0;
}
