#include <bits/stdc++.h>
using namespace std;
bool prime(long long int v) {
  for (long long int i = 3; i * i <= v; i += 2) {
    if (v % i == 0) {
      return false;
    }
  }
  return true;
}
int main() {
  long long int s, t, a[900], p = 0;
  a[897] = 9973219;
  a[896] = 9950539;
  a[895] = 9950209;
  a[894] = 9933619;
  a[893] = 9923989;
  a[892] = 9917059;
  a[891] = 9910759;
  for (t = 0; 30 * t + 19 < 9892040; t++) {
    s = 30 * t;
    if (prime(s + 19)) {
      if (prime(s + 17)) {
        if (prime(s + 13)) {
          if (prime(s + 11)) {
            a[p++] = s + 19;
          }
        }
      }
    }
  }
  p = 898;
  while (1) {
    cin >> s;
    if (s == 0) {
      break;
    }
    if (s < 19) {
      cout << 13 << endl;
      continue;
    }
    t = a[p - 1];
    for (int i = 0; i < p; i++) {
      if (a[i] > s) {
        t = a[i - 1];
        break;
      }
    }
    cout << t << endl;
  }
  return 0;
}
