#include <bits/stdc++.h>
using namespace std;

#define for_(i,a,b) for(int i=(a);i<(b);++i)

int main() {
	vector< int > primes;
	
	vector< bool > isPrime(10000001, true);
	
	for_(i,2,10000001) {
		if (isPrime[i]) {
			primes.push_back(i);
			for (int j = 2 * i; j < 10000001; j += i) isPrime[j] = false;
		}
	}
	
	int n, m = primes.size();
	
	while (cin >> n, n) {
		int ans = 0;
		
		for_(i,3,m) {
			if (primes[i] > n) break;
			
			if (primes[i] - primes[i - 1] == 2 &&
				primes[i - 1] - primes[i - 2] == 4 &&
				primes[i - 2] - primes[i - 3] == 2) {
				ans = primes[i];
			}
		}
		
		cout << ans << endl;
	}
}