/*
 * src.cpp
 *
 *  Created on: 2016/08/04
 *      Author: joi
 */

#include <bits/stdc++.h>

using namespace std;

#define FOR(i,a,b) for(int i=(a);i<(b);i++)
#define REP(i,a) FOR(i,0,a)

const int MAX_N=1e7;

bool prime[MAX_N+1];

void sieve(){
	memset(prime,1,sizeof(prime));
	prime[0]=prime[1]=false;
	for (int i=2;i*i<=MAX_N;i++){
		if (prime[i]){
			for (int j=i*2;j<=MAX_N;j+=i){
				prime[j]=false;
			}
		}
	}
}

int n;

int main(){
	sieve();
	do{
		scanf("%d",&n);
		if (n){
			for (int x=n;;x--){
				if (prime[x] && prime[x-2] && prime[x-6] && prime[x-8]){
					printf("%d\n",x);
					break;
				}
			}
		}
	}while(n);
	return 0;
}