#include <bits/stdc++.h>
using namespace std;
int n, m;
bool prime(int x) {
  for (int i = 2; i * i <= x; i++)
    if (x % i == 0) return false;
  return x > 1;
}
int main() {
  scanf("%d%d", &n, &m);
  int p = n + 1;
  if (!prime(p)) {
    printf("-1\n");
    return 0;
  }
  for (int b = m - 1; b > 1; b--) {
    if (b % p == 0) continue;
    long long t = 0, r = 1, c = 0, x, d;
    while (true) {
      t++;
      x = r * b;
      d = x / p;
      r = x % p;
      c = c * b + d;
      if (r == 1) break;
      if (t > p / 2) {
        printf("%d\n", b);
        return 0;
      }
    }
    if (t == n) {
      printf("%d\n", b);
      return 0;
    }
  }
  printf("-1\n");
  return 0;
}
