include<stdio.h>
#include<math.h>
#define N 1000000

int main(){
	int n;
	int a[N];
	int b;
	int i, j, p;
	int c[N][2];
	p = 1;
	while (1==1){
		scanf("%d", &c[p][0]);
		if(c[p][0]!=0)p++;
		else break;
	}
		b = (int)pow(N, 0.5);
		a[0] = -1;
		for (i = 2; i <= b; i++){
			for (j = 2; j <= N/ i; j++){
				a[i*j - 1] = -1;
			}
		}
	for (i = 1; i < p; i++){	
		c[i][1] = 0;
		for (j = c[i][0];j>0; j--){
			if (a[j - 1] != -1){ 
				if (a[j - 2 - 1] != -1 && a[j - 6 - 1] != -1 && a[j - 8 - 1] != -1){
					c[i][1] = j;
					j = 0;
				}
			}
		}
		printf("%d\n", c[i][1]);
	}

	return 0;
}