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