#include <bits/stdc++.h>
#pragma warning(disable : 4996)
using namespace std;
using ld = long double;
template <class T>
using Table = vector<vector<T>>;
const ld eps = 1e-9;
map<int, bool> mp;
bool isso(long long int a) {
  if (mp.find(a) != mp.end()) return mp[a];
  if (a == 1 || a == 0) return false;
  for (long long int i = 2; i * i <= a; ++i) {
    if ((a % i)) {
    } else {
      return mp[a] = false;
    }
  }
  return mp[a] = true;
}
int main() {
  while (1) {
    int N;
    cin >> N;
    if (!N) break;
    int num = N;
    if (num % 2 == 0) num--;
    while (1) {
      if (isso(num) && isso(num - 2) && isso(num - 6) && isso(num - 8)) {
        cout << num << endl;
        break;
      }
      num -= 2;
    }
    mp.clear();
  }
  return 0;
}
