#include <bits/stdc++.h>
int n;
int i, j;
int a[4];
bool f[100000001];
int ans;
int max(int a, int b) { return a > b ? a : b; }
int main() {
  while (1) {
    scanf("%d", &n);
    if (n == 0) return 0;
    for (i = 0; i < 4; i++) a[i] = 0;
    for (i = 2; i <= n; i++) f[i] = true;
    ans = 13;
    for (i = 2; i <= n; i++) {
      if (f[i]) {
        for (j = 1; i * j <= n; j++) f[i * j] = false;
        a[0] = a[1];
        a[1] = a[2];
        a[2] = a[3];
        a[3] = i;
        if (a[1] == a[0] + 2 && a[2] == a[1] + 4 && a[3] == a[2] + 2)
          ans = max(ans, a[3]);
      }
    }
    printf("%d\n", ans);
  }
}
