#include <bits/stdc++.h>
using namespace std;
__attribute__((constructor)) void initial() {
  cin.tie(0);
  ios::sync_with_stdio(false);
}
int a[10000001];
int ans[10000001];
int main() {
  for (int i = (2); i < (10000001); i++) {
    if (!a[i]) {
      for (int j = i * 2; j < 10000001; j += i) {
        a[j] = 1;
      }
    }
  }
  int sum;
  for (int i = (13); i < (10000001); i++) {
    if (!a[i] && !a[i - 2] && !a[i - 6] && !a[i - 8]) sum = i;
    ans[i] = sum;
  }
  int b;
  while (cin >> b && b) {
    cout << ans[b] << endl;
  }
}
