#include <iostream>
#include <cstring>
using namespace std;

char p[10000001];

void mkPrime(void){
	memset(p,1,sizeof(p));
	p[0] = p[1] = 0;
	for(int i=2;i<=10000000;i++){
		if(p[i]){
			for(int j=i*2;j<=10000000;j+=i){
				p[j] = 0;
			}
		}
	}
}

int main(void){
	mkPrime();

	int n;

	while(cin>>n && n){
		int i = n;
		while(!(p[i] && p[i-2] && p[i-6] && p[i-8])) i--;
		cout<<i<<endl;
	}

	return 0;
}