#include <bits/stdc++.h>
using namespace std;
int N, X, P;
bool isprime(signed long long v) {
  for (signed long long i = 2; i * i <= v; i++)
    if (v % i == 0) return false;
  return true;
}
signed long long modpow(signed long long a, signed long long n,
                        signed long long mo) {
  signed long long r = 1;
  while (n) r = r * ((n % 2) ? a : 1) % mo, a = a * a % mo, n >>= 1;
  return r;
}
bool is_prim_root_modulo(signed long long b, signed long long p) {
  signed long long cur = 1, i;
  if (!isprime(p)) return false;
  for (i = 2; i * i <= p - 1; i++)
    if ((p - 1) % i == 0) {
      if (modpow(b, i, p) == 1) return false;
      if (modpow(b, (p - 1) / i, p) == 1) return false;
    }
  return true;
}
void solve() {
  int i, j, k, l, r, x, y;
  string s;
  cin >> N >> X;
  P = N + 1;
  if (isprime(P)) {
    for (signed long long B = X - 1; B >= 2; B--)
      if (B % P && is_prim_root_modulo(B, P)) return (void)printf("%lld\n", B);
  }
  (void)printf("-1\n");
}
int main(int argc, char** argv) {
  string s;
  int i;
  if (argc == 1) ios::sync_with_stdio(false);
  for (i = 0; i < argc - 1; i++) s += argv[i + 1], s += '\n';
  for (i = 0; i < s.size(); i++) ungetc(s[s.size() - 1 - i], stdin);
  solve();
  return 0;
}
