#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <sstream>
#include <cmath>
#include <queue>

using namespace std;

bool a[10000001];

int main(){
	
	int N = 10000001;
	
	for(int i = 0; i < N; i++){
		a[i] = true;
	}
	
	a[0] = false;
	a[1] = false;
	
	for(int i = 2; i < N; i++){
		if(a[i]){
			for(int j = i * 2; j < N; j += i){
				a[j] = false;
			}
		}
	}
	
	int n;
	
	while(true){
		cin >> n;
		if(n == 0){
			break;
		}
		
		int ans;
		
		for(int i = n; i >= 13; i--){
			if(a[i] && a[i - 2] && a[i - 6] && a[i - 8]){
				ans = i;
				break;
			}
		}
		
		cout << ans << endl;
	}
	
	return 0;
}