#include <bits/stdc++.h>
using namespace std;
int main() {
  while (true) {
    int N;
    scanf("%d", &N);
    if (N == 0) break;
    if (N >= 13 && N <= 18) {
      printf("13\n");
      continue;
    }
    while (true) {
      if (N % 10 != 9) {
        N--;
        continue;
      }
      bool F = true;
      int p = N;
      for (int i = 2; i * i <= p; i++) {
        if (p % i == 0) F = false;
      }
      if (!F) goto next;
      for (int i = 2; i * i <= p - 2; i++) {
        if ((p - 2) % i == 0) F = false;
      }
      if (!F) goto next;
      for (int i = 2; i * i <= p - 6; i++) {
        if ((p - 6) % i == 0) F = false;
      }
      if (!F) goto next;
      for (int i = 2; i * i <= p - 8; i++) {
        if ((p - 8) % i == 0) F = false;
      }
      if (!F) goto next;
    next:;
      if (F) {
        printf("%d\n", N);
        break;
      } else
        N -= 10;
    }
  }
  return 0;
}
