#include<stdio.h>

    char prime[10000001];

int main()
{
    int i,j,n;


    for(i = 2;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]+prime[i-2]+prime[i-6]+prime[i-8]==4) {
                break;
            }   
        }   

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

    }   
    return 0;
}