#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef pair<int, int> P;

#define pb push_back
#define rep(i, a, n) for(int i = (a); i < (n); i++)
#define dep(i, a, n) for(int i = (a); i >= (n); i--)
#define mod 1e9+7

__attribute__((constructor))
void initial() {
  cin.tie(0);
  ios::sync_with_stdio(false);
}

int a[10000001];

int main() {
  rep(i, 2, 10000001) {
    if(!a[i]) {
      for(int j = i * 2; j < 10000001; j += i) {
        a[j] = 1;
      }
    }
  }
  int sum;
  rep(i, 1, 9999993) {
    if(!a[i] && !a[i + 2] && !a[i + 6] && !a[i + 8]) sum = i + 8;
    a[i] = sum;
  }

  int b;
  while(cin >> b && b) {
    cout << a[b - 8] << endl;
  }
}