#include <bits/stdc++.h>
using namespace std;
long long n;
long long arr[10000010], ans[10000010];
void Eratosthenes() {
  for (long long i = 0; i <= 10000010; i++) arr[i] = 1;
  for (long long i = 2; i <= sqrt(10000010); i++) {
    if (arr[i]) {
      for (long long j = 0; i * (j + 2) <= 10000010; j++) arr[i * (j + 2)] = 0;
    }
  }
  long long pre_prime = 0;
  for (long long i = 13; i <= 10000010; i++) {
    if (arr[i] && arr[i - 2] && arr[i - 6] && arr[i - 8]) {
      ans[i] = i;
      pre_prime = i;
    } else
      ans[i] = pre_prime;
  }
}
int main() {
  Eratosthenes();
  while (cin >> n, n) {
    cout << ans[n] << endl;
  }
  return 0;
}
