#include <iostream>
using namespace std;

const int nmax = 10000000;
char nums[nmax];

int main(){
	int n;
	for(int i = 2; i < nmax; i++){
		nums[i] = '1';
	}
	for(int i = 2; i * i < nmax; i++){
		if(nums[i] == '1'){
			for(int k = 2; k * i < nmax; k++){
				nums[i*k] = '0';
			}
		}
	}
	while(cin >> n){
		if(n == 0) break;
		int i = n;
		while(nums[i] == '0' || nums[i-2] == '0' || nums[i-6] == '0' || nums[i-8] == '0') i--;
		cout << i << endl;
	}
	return 0;
}