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

bool check(int q) {
	for (int i = 3; i <= sqrt(q); i += 2)
		if (q % i == 0)
			return 0;

	return 1;
}

int main()
{	
	int n;

	cin >> n;

	while (n > 0) {
		if (n < 19 && n >= 13)
			cout << 13 << endl;
		else {
			int i = n - (n + 11) % 30;

			while (!(check(i) && check(i - 2) && check(i - 6) && check(i - 8)))
				i -= 30;

			cout << i << endl;
		}

		cin >> n;
	}

	return 0;
}

