#include<iostream>
using namespace std;

int prime(int a,int b,int c,int d) {
	for (int e = 3;; e += 2) {
		if (a%e==0 ||b%e==0 ||c%e==0 ||d%e==0)return false;
		if ((e + 1)*(e + 1) > d)return true;
	}
}
int main() {
	while (1) {
		int a;
		cin >>a;
		if (a == 0)break;
		int b = a - (a % 6) + 1;
		if (a % 6 == 0)b = a - 5;
		for (;; b -= 6) {
			if (prime(b, b - 2, b - 6, b - 8)) { cout << b <<endl; break; }
		}
	}
}