#include <bits/stdc++.h>
using namespace std;
long long fast_pow_mod(long long base, int power, int moder) {
  if (power == 0) {
    return 1;
  } else {
    long long res = fast_pow_mod(base, power / 2, moder);
    res = (res * res) % moder;
    if (power % 2 == 0) {
      return res;
    } else {
      return (res * base) % moder;
    }
  }
}
int main() {
  int n, x;
  scanf("%d%d", &n, &x);
  const int LEN = 5000001;
  vector<bool> isprime(LEN + 1, true);
  for (int p = 2; p <= LEN; ++p) {
    if (isprime[p]) {
      for (int n = 2; n * p <= LEN; ++n) {
        isprime[n * p] = false;
      }
    }
  }
  if (x - 1 >= 2) {
    if (n == 1) {
      printf("%d\n", x - 1);
    } else if (isprime[n + 1]) {
      vector<int> divs;
      divs.reserve(n);
      for (int i = 2; i < n; ++i) {
        if (n % i == 0) {
          divs.push_back(i);
        }
      }
      bool have_ans = false;
      for (int b = x - 1; b >= max(2, x - 1 - n); --b) {
        if (b % (n + 1) != 0) {
          bool valid = true;
          for (int div : divs) {
            if (fast_pow_mod(b % (n + 1), div, n + 1) == 1) {
              valid = false;
              break;
            }
          }
          if (valid) {
            printf("%d\n", b);
            have_ans = true;
            break;
          }
        }
      }
      if (!have_ans) {
        puts("-1");
      }
    } else {
      puts("-1");
    }
  } else {
    puts("-1");
  }
  return 0;
}
