#include <bits/stdc++.h>
using namespace std;
int num[10000001] = {};
vector<int> V;
void f() {
  num[0] = num[1] = 1;
  for (int i = 2; i < 10000001; i++) {
    if (!num[i]) {
      for (int j = 2; i * j < 10000001; j++) num[i * j] = 1;
    }
  }
  V.push_back(0);
  for (int i = 13; i < 10000001; i++) {
    if (!num[i] && !num[i - 2] && !num[i - 6] && !num[i - 8]) {
      V.push_back(i);
    }
  }
}
int main() {
  f();
  int n;
  while (cin >> n, n) {
    int pos;
    for (pos = 1; pos < V.size(); pos++) {
      if (V[pos] > n) {
        cout << V[--pos] << endl;
        break;
      }
    }
  }
}
