#include <bits/stdc++.h>
const double PI = acos(-1);
const double ESP = 1e-10;
using namespace std;
bool num[10000010] = {1, 1, 0};
int main() {
  for (int i = 3; i < 10000010; i += 2) {
    if (num[i] == 1) continue;
    for (int j = 3 * i; j < 10000010; j += i * 2) num[j] = 1;
  }
  for (int i = 4; i < 10000010; i += 2) num[i] = 1;
  vector<long long int> ans;
  for (int i = 13; i < 10000010; i++) {
    if (!(num[i] || num[i - 2] || num[i - 6] || num[i - 8])) ans.push_back(i);
  }
  sort(ans.begin(), ans.end());
  int in;
  while (cin >> in, in) {
    int k;
    for (int i = 0; i < ans.size(); i++)
      if (ans[i] > in) {
        k = i - 1;
        break;
      }
    cout << ans[k] << endl;
  }
}
