#include <bits/stdc++.h>
using namespace std;
int n, m;
long long mpow(long long x, long long y, long long mod) {
  long long t = 1;
  while (y) {
    if (y & 1) t = t * x % mod;
    y >>= 1, x = x * x % mod;
  }
  return t;
}
int main(void) {
  scanf("%d%d", &n, &m);
  if (n == 1) return printf("%d\n", m > 2 ? m - 1 : -1), 0;
  for (int i = 2; i <= (n + 1) / i; i++)
    if ((n + 1) % i == 0) puts("-1"), exit(0);
  for (int i = m - 1; i >= 2; i--) {
    bool sign = true;
    for (int j = 2; j <= n / j && sign; j++)
      if (n % j == 0)
        sign &= !(mpow(i, j, n + 1) == 1 || mpow(i, n / j, n + 1) == 1);
    if (sign) {
      printf("%d\n", i);
      return 0;
    }
  }
  puts("-1");
  return 0;
}
