#include <bits/stdc++.h>
using namespace std;
int n, x, i, FLAG, p[100005], cnt, m;
int quick(int a, int b) {
  int ans = 1;
  while (b) {
    if (b & 1) ans = 1ll * ans * a % n;
    a = 1ll * a * a % n;
    b /= 2;
  }
  return ans;
}
bool OK(int x) {
  for (int i = 1; i <= cnt; i++)
    if (quick(x, p[i]) == 1) return false;
  return true;
}
int main() {
  scanf("%d%d", &n, &x);
  FLAG = 0;
  if (n == 1 && x == 2) {
    cout << -1;
    return 0;
  }
  for (i = 2; i <= int(sqrt(n + 1)); i++)
    if ((n + 1) % i == 0) FLAG = 1;
  if (FLAG) {
    cout << -1;
    return 0;
  }
  m = n;
  for (i = 2; i <= m; i++) {
    if (m % i == 0) p[++cnt] = n / i;
    while (m % i == 0) m /= i;
  }
  n++;
  while (--x)
    if (OK(x)) {
      cout << x;
      return 0;
    }
  cout << -1;
  return 0;
}
