#include <bits/stdc++.h>
using namespace std;
int main() {
  bool p[100000];
  p[0] = p[1] = false;
  for (int i = 2; i < 100000; i++) {
    p[i] = true;
  }
  for (int i = 2; i * i < 100000; i++) {
    if (p[i])
      for (int j = i * i; j < 100000; j += i) {
        p[j] = false;
      }
  }
  while (1) {
    bool x = true;
    int N;
    cin >> N;
    if (N == 0) break;
    for (int i = N; i != 0; i--) {
      if (p[i - 8])
        if (p[i - 6])
          if (p[i - 2])
            if (p[i])
              if (x) {
                cout << i << endl;
                x = false;
              }
    }
  }
  return 0;
}
