#include <algorithm>
#include <iostream>
#define rep(i, n) for(int i = 0; i < n; ++i)
using namespace std;

const int N = 10000000;
bool prime[N];

void sieve() {
	rep(i, N) prime[i] = true;
	prime[0] = prime[1] = false;
	for(int i = 2; i < N; ++i) {
		if(prime[i])	for(int j = 2 * i; j < N; j+=i) prime[j] = false;
	}
}

int main() {
	sieve();
	int n;
	while(cin>>n, n){
		int i = n;
		while(!(prime[i] && prime[i-2] && prime[i-6] && prime[i-8])) --i;
		cout << i << endl;
  }
}