#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cfloat>
#include <map>
#include <utility>
#include <set>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include <algorithm>
#include <functional>
#include <sstream>
#include <complex>
#include <stack>
#include <queue>
#include <cstring>
using namespace std;
static const double EPS = 1e-5;
typedef long long ll;


char so[10000001];

int main(){
	so[0]=so[1]=1;
	
	for(int i=2;i*i<=10000000;i++){
		if(so[i]==1)continue;
		for(int j=i;j*i<=10000000;j++){
			so[j*i]=1;
		}
	}
	
	int n;
	while(cin>>n){
		if(n==0)break;
		
		while(1){
			if(so[n]|so[n-2]|so[n-6]|so[n-8]);
			else break;
			--n;
		}
		
		cout<<n<<endl;
	}
	return 0;
}