#include <bits/stdc++.h>
using namespace std;
int num[10000001] = {};
int ans[10000001] = {};
void f() {
  num[0] = num[1] = 1;
  for (int i = 2; i < 10000001; i++) {
    if (!num[i]) {
      for (int j = 2; i * j < 10000001; j++) num[i * j] = 1;
    }
  }
  int MAX_NUM = 13;
  for (int i = 13; i < 10000001; i++) {
    if (!num[i] && !num[i - 2] && !num[i - 6] && !num[i - 8]) MAX_NUM = i;
    ans[i] = MAX_NUM;
  }
}
int main() {
  f();
  int n;
  while (cin >> n, n) cout << ans[n] << endl;
}
