#include <bits/stdc++.h>
using namespace std;
bool prime[10000000] = {};
int yo[10000000] = {};
int main() {
  prime[1] = true;
  prime[2] = false;
  for (int i = 3; i < 10000000; i++) {
    if (!prime[i])
      for (int j = 2; i * j < 10000000; j++) {
        prime[i * j] = true;
      }
  }
  for (int i = 13; i < 10000000; i++) {
    if (!prime[i - 8] && !prime[i - 6] && !prime[i - 2] && !prime[i]) {
      yo[i] = i;
    } else
      yo[i] = yo[i - 1];
  }
  int n;
  while (1) {
    cin >> n;
    if (n == 0) break;
    cout << yo[n] << "\n";
  }
}
