#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"

long long int powmod(long long int a, long long int b, const int mod) {
	assert(b >= 0);
	if (b == 0)return 1;
	if (b == 1)return a;
	long long int ans = 1;
	long long int aa = powmod(a, b / 2, mod);
	ans *= aa*aa;
	ans %= mod;
	if (b % 2)ans *= a;
	ans %= mod;
	return ans;
}

const int k = 12;
//?´???°??????
bool mirror_rabin(const long long int n) {
	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;
}
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;
		if (num < 19) {
			cout << 13 << endl;
		}
		else {
			while (num % 30 != 19)num--;
			while (1) {
				if (mirror_rabin(num) && mirror_rabin(num - 2) && mirror_rabin(num - 6) && mirror_rabin(num - 8)) {
					cout << num << endl;
					break;
				}
				num -= 30;
			}
		}
	}
	return 0;
}