#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;
long long int powmod(long long int a, long long int b, const int mod) {
  assert(b >= 0);
  if (b == 0) return 1;
  if (b == 1) return a;
  long long int ans = 1;
  long long int aa = powmod(a, b / 2, mod);
  ans *= aa * aa;
  ans %= mod;
  if (b % 2) ans *= a;
  ans %= mod;
  return ans;
}
const int k = 20;
bool mirror_rabin(const long long int n) {
  if (n == 2) return true;
  if (n == 1 || (n & 1) == 0) return true;
  int s = 0;
  int d = n - 1;
  while (!(d % 2)) {
    s++;
    d /= 2;
  }
  for (int i = 0; i < k; ++i) {
    const long long int a = rand() % (n - 1) + 1;
    long long int t = d;
    long long int y = powmod(a, t, n);
    while (t != n - 1 && y != 1 && y != n - 1) {
      y = (y * y) % n;
      t <<= 1;
    }
    if (y != n - 1 && (t & 1) == 0) return false;
  }
  return true;
}
bool isso(long long int a) {
  return mirror_rabin(a);
  if (a == 1 || a == 0) return false;
  for (long long int i = 2; i * i <= a; ++i) {
    if ((a % i)) {
    } else {
      return false;
    }
  }
  return true;
}
int main() {
  while (1) {
    int N;
    cin >> N;
    if (!N) break;
    int num = N;
    if (num < 19) {
      cout << 13 << endl;
    } else {
      while (num % 30 != 19) num--;
      while (1) {
        if (mirror_rabin(num) && mirror_rabin(num - 2) &&
            mirror_rabin(num - 6) && mirror_rabin(num - 8)) {
          cout << num << endl;
          break;
        }
        num -= 30;
      }
    }
  }
  return 0;
}
