#include <bits/stdc++.h>
const double PI = acos(-1);
const double EPS = 1e-10;
using namespace std;
bool sosu[10000100];
int main() {
  bool sosu[10000100];
  memset(sosu, true, 10000100);
  for (int i = 4; i < 10000100; i += 2) sosu[i] = false;
  for (int i = 3; i < 10000100; i += 2)
    for (int j = 3 * i; j < 10000100; j += 2 * i) sosu[j] = false;
  int n;
  while (cin >> n, n) {
    for (int i = n; i >= 0; i--) {
      if (sosu[i] && sosu[i - 2] && sosu[i - 6] & sosu[i - 8]) {
        cout << i << endl;
        break;
      }
    }
  }
}
