#include <bits/stdc++.h>
using namespace std;
int main() {
  bool p[100000];
  p[0] = p[1] = false;
  for (int i = 2; i < 100000; i++) {
    p[i] = true;
  }
  for (int i = 2; i * i < 100000; i++) {
    if (p[i])
      for (int j = i * i; j < 100000; j += i) {
        p[j] = false;
      }
  }
  while (1) {
    int count = 0;
    int N;
    cin >> N;
    if (N == 0) break;
    for (int i = N; i != 0; i--) {
      if (p[i - 8] && p[i - 6] && p[i - 2] && p[i]) {
        cout << i << endl;
        break;
      }
    }
  }
  return 0;
}
