#include <bits/stdc++.h>
using namespace std;
const int oo = 0x3f3f3f3f;
const double eps = 1e-9;
long long exp_mod(long long a, long long x, long long m) {
  if (x == 0) return 1;
  long long res = exp_mod(a, x / 2, m);
  res = (res * res) % m;
  return (x % 2) ? (res * a) % m : res;
}
int main() {
  ios_base::sync_with_stdio(false);
  long long n, x;
  cin >> n >> x;
  if (x == 2) {
    cout << -1 << endl;
    return 0;
  }
  if (n == 1) {
    cout << x - 1 << endl;
    return 0;
  }
  long long p = n + 1;
  for (long long i = 2; i * i <= p; i++) {
    if (p % i == 0) {
      cout << -1 << endl;
      return 0;
    }
  }
  vector<int> facs;
  long long tmp = n;
  for (long long i = 2; i * i <= tmp; i++) {
    if (tmp % i) continue;
    facs.push_back(i);
    while (tmp % i == 0) tmp /= i;
  }
  if (tmp > 1) facs.push_back(tmp);
  for (int k = (x)-1; k >= (max(1ll, x - p)); k--) {
    long long v = k % p;
    bool pr = true;
    for (const long long &f : facs) {
      if (exp_mod(v, n / f, p) == 1) {
        pr = false;
        break;
      }
    }
    if (pr) {
      cout << k << endl;
      return 0;
    }
  }
  cout << -1 << endl;
  return 0;
}
