#include <bits/stdc++.h>
const int MAX = 10000010;
using namespace std;
bool p[MAX];
void sieve_of_eratosthenes() {
  for (int i = 0; i < MAX; i++) {
    p[i] = (i <= 1) ? false : true;
  }
  for (int i = 2; i <= sqrt((double)MAX) + 1; i++) {
    if (p[i]) {
      for (int j = i * 2; j < MAX; j += i) {
        p[j] = false;
      }
    }
  }
}
int main() {
  int n, m = 13;
  sieve_of_eratosthenes();
  while (cin >> n, n) {
    for (int i = 2; i < MAX; ++i) {
      if (p[i] && p[i + 2] && p[i + 6] && p[i + 8]) {
        if (i + 8 > n) break;
        m = i + 8;
      }
    }
    cout << m << endl;
  }
}
