#include<iostream>

#define MAX 10000001

bool isPrime[MAX];

int main(){

	for (int i = 2; i < MAX; i++){
		isPrime[i] = true;
	}

	for (int i = 2; i*i < MAX; i++){
		if (isPrime[i]){
			for (int j = i * 2; j < MAX; j += i)isPrime[j] = false;
		}
	}

	int n;
	while (std::cin >> n, n){
		for (int i = n; i >= 8; i--){
			if (isPrime[i] && isPrime[i - 2] && isPrime[i - 6] && isPrime[i - 8]){
				std::cout << i << std::endl;
				break;
			}
		}
	}

	return 0;
}