#include<stdio.h>
#include<bitset>
const int N=10000001;
std::bitset<N>p;
int main()
{
	p.set();
	int i,j;
	for(i=2;i*i<N;++i)if(p[i])for(j=i*i;j<N;j+=i)p[j]=0;
	while(scanf("%d",&i),i)
	{
		i-=(i-1)%6;
		while(!(p[i]&&p[i-2]&&p[i-6]&&p[i-8]))i-=6;
		printf("%d\n",i);
	}
	return 0;
}