#include <iostream>
#define rep2(x,from,to) for(int x=(from);(x)<(to);(x)++)
#define rep(x,to) rep2(x,0,to)
using namespace std;
const int MAX = 10000001;
bool p[MAX];

int main(){
	p[0] = p[1] = 1;
	for(int i = 2; i*i < MAX; ++i) {
		if(!p[i]) {
			for(int j = i*i; j < MAX; j+=i) {
				p[j] = 1;
			}
		}
	}
	int n;
	while(cin >> n, n) {
		for(int i = n; i >= 13; i--) {
			if(!p[i] && !p[i-2] && !p[i-6] && !p[i-8]) {
				cout << i << endl;
				break;
			}
		}
	}
}