#include <bits/stdc++.h>
using namespace std;
int main() {
  while (1) {
    const int n = 10000001;
    int array[n];
    int num;
    cin >> num;
    if (num == 0) break;
    for (int i = 1; i <= num; i++) {
      array[i] = i;
    }
    array[1] = 0;
    array[3] = 0;
    for (int i = 5; i <= num; i++) {
      for (int j = 2; j < array[i]; j++) {
        if (array[i] % j == 0) {
          array[i] = 0;
          break;
        }
      }
    }
    for (int i = num; i > 0; i--) {
      if (array[i] > 0 && array[i - 2] > 0 && array[i - 6] > 0 &&
          array[i - 8] > 0) {
        cout << array[i] << endl;
        break;
      }
    }
  }
  return 0;
}
