#include <stdio.h>
#include <cmath>
#include <algorithm>

#define NUM 11000001


int main(){
	int* table = new int[NUM];
	int limit,p;
	int* info = new int[2000000];
	p = 0;

	for(int i=0; i < NUM;i++)table[i] = 1;
	table[0] = 0;
	table[1] = 0;

	limit = sqrt(NUM);

	for(int i=2;i<=limit;i++){
		if(table[i] == 1){
			for(int k=2*i;k < NUM; k += i){
				table[k] = 0;
			}
		}
	}

	info[0] = 13;
	p++;
	for(int i = 17; i <= 11000000; i += 2){
		if(table[i] == 1 && table[i-2] == 1 && table[i-6] == 1 && table[i-8] == 1)
			info[p++] = i;
	}

	int n;

	while(true){
		scanf("%d",&n);
		if(n == 0)break;

		for(int i = 0; i < p; i++){
			if(info[i] > n){
				printf("%d\n",info[i-1]);
				break;
			}
		}
	}
	return 0;
}