#include <bits/stdc++.h>
using namespace std;

int prime[10000005] = {1, 1};
int print[10000005] = {-1, -1, 2};

int main()
{
    int i, j;

    for (i = 2; i * i < 10000005; i++) {
        if (prime[i] == 1) continue;
        for (j = 2; i * j < 10000005; j++) {
            prime[i * j] = 1;
        }
    }
    for (i = 13; i + 8 < 10000005; i++) {
        if (prime[i - 8] == 0 && prime[i- 2] == 0 && prime[i - 6] == 0 && prime[i] == 0) {
            print[i] = i;
        } else {
            print[i] = print[i - 1];
        }
    }

    int n;
    cin >> n;
    while (n != 0) {
        printf("%d\n", print[n]);

        cin >> n;
    }

    return 0;
}

