#include <bits/stdc++.h>
#define rep(i,n)for(int i=0;i<n;i++)
using namespace std;
typedef long long ll;
typedef pair<int, int>P;

int is_prime[10000001];
int prime[10000001];
int main() {
	memset(is_prime, 1, sizeof(is_prime));
	is_prime[0] = is_prime[1] = false;
	int p = 0;
	for (int i = 2; i < 10000001; i++) {
		if (is_prime[i]) {
			prime[p++] = i;
			for (int j = i * 2; j <= 10000001; j += i)is_prime[j] = false;
		}
	}
	int i;
	while (scanf("%d", &i), i) {
		int j = lower_bound(prime, prime + p, i) - prime;
		for (int ans = j;; ans--) {
			if (prime[ans] <= i&&prime[ans] - prime[ans - 3] == 8) {
				printf("%d\n", prime[ans]); break;
			}
		}
	}
	return 0;
}