#include <bits/stdc++.h>
bool isPrime(uint64_t n) {
  if (n <= 1) return false;
  if (n <= 3) return true;
  if (n % 2 == 0 || n % 3 == 0) return false;
  uint64_t i = 5;
  while (i * i <= n) {
    if (n % i == 0 || n % (i + 2) == 0) return false;
    i += 6;
  }
  return true;
}
uint64_t modPow(uint64_t a, uint64_t n, uint64_t mo) {
  uint64_t r = 1;
  while (n) {
    r = r * ((n % 2) ? a : 1) % mo;
    a = a * a % mo;
    n >>= 1;
  }
  return r;
}
bool isPrimRootModulo(uint64_t b, uint64_t p) {
  if (!isPrime(p)) return false;
  for (uint64_t i = 2; i * i <= p - 1; i++) {
    if ((p - 1) % i == 0) {
      if (modPow(b, i, p) == 1) return false;
      if (modPow(b, (p - 1) / i, p) == 1) return false;
    }
  }
  return true;
}
int main() {
  uint64_t n, x;
  std::cin >> n >> x;
  uint64_t p = n + 1;
  if (isPrime(p)) {
    for (uint64_t b = x - 1; b >= 2; b--)
      if (b % p && isPrimRootModulo(b, p)) {
        std::cout << b << "\n";
        return 0;
      }
  }
  std::cout << "-1\n";
  return 0;
}
