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