#include<stdio.h>

int main(void)
{
    int i,j,n;
    char prime[10000001];

    for(i = 0;i <= 10000000;i++){
prime[i]='1';
}

    for(i = 2;i <= 10000000;i++){
if(prime[i]){
for(j=i+i;j<=10000000;j+=i){
prime[j]='0';
}
}
}

    while(scanf("%d",&n),n){

        if(n%2==0){
n--;
}

        for(i=n;i>=13;i-=2){
            if(prime[i]=='1'&&prime[i-2]=='1'&&prime[i-6]=='1'&&prime[i-8]=='1') {
                break;
            }   
        }   

        printf("%d\n",i);

    }   }
    return (0);
}