#include<stdio.h>
#include<algorithm>
char prime[10000001];
int main(){
	
	for(int i=2;i*i<=10000000;i++){
		if(prime[i]==0){
			prime[i]=1;
			for(int j=i*2;j<=10000000;j+=i)prime[j]=-1;
		}
	}
	for(int i=3162;i<=10000000;i++)if(prime[i]==0)prime[i]=1;
	int a;
	while(scanf("%d",&a),a){
		do{
			if(a>7&&prime[a]==1&&prime[a-2]==1&&prime[a-6]==1&&prime[a-8]==1){
				printf("%d\n",a);
				break;
			}
		}while(a--);
		if(a==0)printf("0\n");
	}
}