#include <bits/stdc++.h>
using namespace std;
int main() {
  bool hantei[10000000];
  vector<int> data;
  vector<int> ans;
  hantei[0] = hantei[1] = false;
  for (int i = 0; i <= 10000000; i += 2) hantei[i] = false;
  hantei[2] = true;
  for (int i = 3; i <= 10000000; i += 2) {
    hantei[i] = true;
  }
  int limit = (int)sqrt((double)10000000) + 1;
  for (int i = 3; i <= limit; i += 2) {
    if (hantei[i] == false) continue;
    for (int j = i + i; j <= 10000000; j += i) hantei[j] = false;
  }
  for (int i = 0; i <= 10000000; i++) {
    if (hantei[i] == true) data.push_back(i);
  }
  for (int i = 0; i + 3 < 20; i++) {
    if ((data[i] + 2) == data[i + 1] && (data[i] + 6) == data[i + 2] &&
        (data[i] + 8) == data[i + 3]) {
      ans.push_back(data[i + 3]);
    }
  }
  while (1) {
    int n;
    int f = 0;
    int temp;
    cin >> n;
    if (n == 0) break;
    for (int i = 0; i < ans.size(); i++) {
      if (ans[i] <= n) temp = ans[i];
      if (ans[i] > n) {
        cout << ans[i - 1] << endl;
        f = 1;
      }
    }
    if (f == 0) cout << temp << endl;
  }
  return 0;
}
