#include <cstdio>

#define N 10000000
#define SQRT_N 3163

bool tmp[N];

void makePrimeList() {
	tmp[0] = tmp[1] = false;

	for(int i = 2; i < N; i++)
		tmp[i] = true;

	for(int i = 2; i < SQRT_N; i++)
		if(tmp[i] == true)
			for(int j = 2; j * i < N; j++)
				tmp[j * i] = false;
}

bool IsPrime(int n) {
	return tmp[n];
}

int retqp(int n) {
	if(n % 2 == 0)
		n--;
	while(!(IsPrime(n - 8) && IsPrime(n - 6) && IsPrime(n - 2) && IsPrime(n)))
		n -= 2;
	return n;
}

int main(void) {
	makePrimeList();
	while(true) {
		int n; scanf("%d", &n);
		if(n == 0)
			break;
		printf("%d\n", retqp(n));
	}
	return 0;
}