#include <bits/stdc++.h>
using namespace std;
int main() {
  int n, a[900], p = 0;
  char prime[9973219 + 1];
  fill(prime, prime + (9973219 + 1), 1);
  prime[0] = prime[1] = 0;
  for (int i = 2; i <= 9973219; i++) {
    if (prime[i]) {
      for (int j = 2 * i; j <= 9973219; j += i) {
        prime[j] = 0;
      }
    }
  }
  for (int i = 0; i + 19 <= 9973219; i += 30) {
    if (prime[i + 11] && prime[i + 13] && prime[i + 17] && prime[i + 19]) {
      a[p++] = i + 19;
    }
  }
  while (1) {
    cin >> n;
    if (n == 0) {
      break;
    }
    if (n < 19) {
      cout << 13 << endl;
      continue;
    }
    if (9973219 < n) {
      cout << 9973219 << endl;
    }
    for (int i = 1; i < p; i++) {
      if (a[i] > n) {
        n = i - 1;
        break;
      }
    }
    cout << a[n] << endl;
  }
  return 0;
}
