#include "bits/stdc++.h"
#include<unordered_map>
#include<unordered_set>
#pragma warning(disable:4996)
using namespace std;
using ld = long double;
template<class T>
using Table = vector<vector<T>>;
const ld eps=1e-9;

//// < "D:\D_Download\Visual Studio 2015\Projects\programing_contest_c++\Debug\a.txt"

bool isso(long long int a) {
	if (a == 1 || a == 0)return false;
	for (long long int i = 2; i*i <= a; ++i) {
		if ((a%i)) {
		}
		else {
			return false;
		}
	}
	return true;
}
int main() {
	while (1) {
		int N; cin >> N;
		if (!N)break;
		int num = N;
		while (num % 6 != 1)num--;
		while (1) {
			if (isso(num) && isso(num - 2) && isso(num - 6) && isso(num - 8)) {
				cout << num << endl;
				break;
			}
			num-=6;
		}
		mp.clear();

	}
	return 0;
}