#include <bits/stdc++.h>
using namespace std;
int n, x;
bool isp(int n) {
  if (n == 1) return false;
  for (long long i = 2; i * i <= n; ++i)
    if (n % i == 0) return false;
  return true;
}
int mpow(long long x, int k) {
  long long ans = 1;
  while (k > 0) {
    if (k & 1) ans = (ans * x) % n;
    x = (x * x) % n;
    k /= 2;
  }
  return ans;
}
int main() {
  cin >> n >> x;
  ++n;
  if (!isp(n)) {
    cout << "-1";
    return 0;
  }
  int m = n - 1;
  vector<int> p;
  for (int i = 2; i <= m; ++i) {
    if (m % i == 0) {
      p.push_back(i);
      while (m % i == 0) m /= i;
    }
  }
  if (m > 1) p.push_back(m);
  for (int y = x - 1; y > 0; --y) {
    bool ok = true;
    for (int i = 0; i < p.size(); ++i) {
      int k = (n - 1) / p[i];
      if (mpow(y % n, k) == 1) {
        ok = false;
        break;
      }
    }
    if (ok) {
      cout << y;
      return 0;
    }
  }
  cout << "-1";
  return 0;
}
