#include<iostream>
using namespace std;
int main(){
	int n, count=0;
	int temp = 0;
	int maxn = 0;
	int sosuu[3] = { 0 };
	cin >> n;
	while (n != 0){
		for (int i = 2; i <= n - 8; i++){
			for (int l = 2; l < i; l++){
				if (i%l == 0) count++;
			}
			if (count == 0) {
				temp = i;
				sosuu[0] = temp + 2;
				sosuu[1] = temp + 6;
				sosuu[2] = temp + 8;
				if (sosuu[2]>maxn){
					for (int i1 = 0; i1 < 3; i1++){
						for (int l1 = 2; l1 < sosuu[i1]; l1++){
							if (sosuu[i1] % l1 == 0) count++;
						}if (count != 0) break;
					}if (count == 0){
						if (maxn < sosuu[2]) maxn = sosuu[2];
					}
				}
			}
			count = 0;
		}
		cout << maxn << endl;
		cin >> n;
	}