#include <bits/stdc++.h>
using namespace std;
template <typename T, typename TT>
ostream& operator<<(ostream& out, pair<T, TT> t) {
  return out << "(" << t.first << "," << t.second << ")";
}
template <typename T>
ostream& operator<<(ostream& out, vector<T> t) {
  for (int i = 0; i < ((int)(t).size()); i++) out << t[i] << " ";
  return out;
}
template <typename T>
inline bool cmin(T& a, const T& b) {
  return a > b ? a = b, 1 : 0;
}
template <typename T>
inline bool cmax(T& a, const T& b) {
  return a < b ? a = b, 1 : 0;
}
template <typename T>
void read(T& x) {
  int f = 1;
  char ch;
  x = 0;
  while (!isdigit(ch = getchar()))
    ;
  while (isdigit(ch)) x = x * 10 + ch - '0', ch = getchar();
  x *= f;
}
int n, x;
bool isprime(int x) {
  for (int i = 2; i * i <= x; i++)
    if (!(x % i)) return false;
  return true;
}
int qow(int a, int b, int mod) {
  int res = 1;
  while (b) {
    if (b & 1) res = (long long)res * a % mod;
    a = (long long)a * a % mod;
    b >>= 1;
  }
  return res;
}
int main() {
  read(n);
  read(x);
  ++n;
  if (!isprime(n)) return puts("-1"), 0;
  for (int g = x - 1; g > 1; g--) {
    int u = n - 1;
    bool ok = true;
    for (int d = 1; d * d <= n && ok; d++)
      if (!(u % d))
        if ((d < u && qow(g, d, n) == 1) ||
            (u / d < u && qow(g, u / d, n) == 1))
          ok = false;
    if (ok) {
      printf("%d\n", g);
      return 0;
    }
  }
  puts("-1");
  return 0;
}
