#include <bits/stdc++.h>
int n, x;
inline bool IsPrime(int x) {
  if (x == 1) return false;
  for (int i = 2; i * i <= x; i++)
    if (x % i == 0) return false;
  return true;
}
long long QPower(long long b, int q, int p) {
  long long rep = 1;
  while (q) {
    if (q & 1) rep = rep * b % p;
    q >>= 1;
    b = b * b % p;
  }
  return rep;
}
int main() {
  scanf("%d%d", &n, &x);
  if (!IsPrime(n + 1)) {
    printf("-1\n");
    return 0;
  }
  for (int i = x - 1; i > 1; i--) {
    bool Ok = true;
    for (int j = 2; j * j <= n && Ok; j++)
      if (n % j == 0)
        if (QPower(i, j, n + 1) == 1 || QPower(i, n / j, n + 1) == 1)
          Ok = false;
    if (Ok) {
      printf("%d\n", i);
      return 0;
    }
  }
  printf("-1\n");
  return 0;
}
