#include<iostream>

bool isPrime(int a){
	bool ans = true;
	for(int i = 3; i*i <= a; i+=2){
		if(a%i == 0 || (a-2)%i == 0 || (a-6)%i == 0 || (a-8)%i == 0){
			ans = false;
			break;
		}
	}
	return ans;
}

int n;

int main(){
	while(true){
		std::cin >> n;
		if(!n)
			return 0;
		if(n%2 == 0)
			n--;
		for(; n>12; n-=2){
			if(isPrime(n)){
				std::cout << n << std::endl;
				break;
			}
		}
	}
}