#include <bits/stdc++.h>
using namespace std;
const int maxn = 5e6 + 10;
bool isp[maxn];
int prime[maxn], use[maxn];
int cnt = 0;
void init() {
  memset(isp, 1, sizeof isp);
  isp[1] = 0;
  for (int i = 2; i <= 5000001; ++i) {
    if (isp[i]) prime[++cnt] = i;
    for (int j = 1; j <= cnt && i * prime[j] <= 5000001; ++j) {
      isp[i * prime[j]] = 0;
      if (i % prime[j] == 0) break;
    }
  }
}
int n, x;
int fpw(int x, int t) {
  if (!t) return 1;
  int cur = fpw(x, t >> 1);
  cur = 1ll * cur * cur % (n + 1);
  if (t & 1) cur = 1ll * cur * x % (n + 1);
  return cur;
}
int main() {
  init();
  cin >> n >> x;
  if (n == 1) {
    if (x == 2)
      cout << -1 << endl;
    else
      cout << x - 1 << endl;
    return 0;
  }
  if (!isp[n + 1]) {
    cout << -1 << endl;
    return 0;
  }
  int sum = 0;
  for (int i = 1; i <= cnt; ++i)
    if (n % prime[i] == 0) use[++sum] = n / prime[i];
  for (int i = x - 1; i > 1; --i) {
    bool flag = 1;
    if (i % (n + 1) == 0) continue;
    for (int j = 1; j <= sum; ++j)
      if (fpw(i, use[j]) == 1) {
        flag = 0;
        break;
      }
    if (flag) {
      cout << i << endl;
      return 0;
    }
  }
  cout << -1 << endl;
  return 0;
}
