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

bool prime[10000005];
vector < int > yotsugo;

int main()
{
    int N;
    fill_n(prime, 10000005, true);

    for ( int i = 2; i < 3335; i++ ) {
        if ( prime[i] ) {
            for ( int j = i * i; j < 10000005; j += i ) {
                prime[j] = false;
            }
        }
    }
    for ( int i = 5; i <= 10000000 - 8; i++ ) {
        if ( prime[i] && prime[i + 2] && prime[i + 6] && prime[i + 8] ) {
            yotsugo.push_back(i + 8);
        }
    }

    while ( cin >> N , N != 0 ) {
        cout << *(upper_bound(yotsugo.begin(), yotsugo.end(), N) - 1) << endl;
    }

    return ( 0 );
}

