#define MAX 10000000
c[MAX/2];
main(){
	int a,b,n;
	for(a=3;a<MAX;a+=2)
		for(b=a;(b+=a*2)<MAX;)
			c[b/2]=1;
	for(;scanf("%d",&n),n;){
		for(;n%2==0||c[n/2]||c[n/2-1]||c[n/2-3]||c[n/2-4];n--);
		printf("%d\n",n);
	}
	{int n;for(n=1000000;n--;)getchar();}//delay(0.52s)
	exit(0);
}