#include<iostream>
using namespace std;

int main(){

  long n,d;

  while(cin >> n, n){

    while(n >= 13){

      d = 0;

      if(n%2 == 1){
	for(int i=3;i*i<=n;i+=2){
	  if(d == 1) break;

	  if(i*i <= n-8){
	    if((n-8)%i == 0) d = 1;
	  }
	  if(i*i <= n-6){
	    if((n-6)%i == 0) d = 1;
	  }
	  if(i*i <= n-2){
	    if((n-2)%i == 0) d = 1;
	  }
	  if(n%i == 0) d = 1;
	}
	n -= 2;
      }

      else{
	n--;
	continue;
      }

      if(!d){
	cout << n+2 << endl;
	break;
      }
    }

  }
}