#include <bits/stdc++.h>
int main(void) {
  int n, i, j, flg, w, a, b, c, d;
  while (1) {
    scanf("%d", &n);
    if (n == 0) break;
    a = 0;
    b = 0;
    c = 0;
    d = 0;
    for (i = n; i >= 5; i--) {
      flg = 1;
      for (j = 2; j < i / 2; j++) {
        w = i % j;
        if (w == 0) {
          flg = 0;
          break;
        }
      }
      if (flg == 1) {
        d = c;
        c = b;
        b = a;
        a = i;
      }
      if (d == c + 2 && d == b + 6 && d == a + 8) break;
    }
    printf("%d\n", d);
  }
  return 0;
}
