#include <bits/stdc++.h>
using namespace std;
long long n, x;
vector<long long> pdiv;
bool is_prime(long long m) {
  for (int i = 2; i * i <= m; i++) {
    if (m % i == 0) return false;
  }
  return true;
}
void get_pdiv(long long m) {
  for (int i = 2; i * i <= m; i++) {
    if (m % i == 0) {
      pdiv.push_back(i);
      while (m % i == 0) m /= i;
    }
  }
  if (m > 1) pdiv.push_back(m);
}
long long mpow(long long a, long long b, long long c) {
  if (b == 0) return 1;
  long long y = mpow(a, b / 2, c);
  y = (y * y) % c;
  if (b % 2 == 0) return y;
  return (y * a) % c;
}
int main() {
  scanf("%I64d %I64d", &n, &x);
  if (!is_prime(n + 1)) {
    printf("-1\n");
    return 0;
  }
  get_pdiv(n);
  for (long long b = x - 1; b >= 2; b--) {
    if (b % (n + 1) == 0) continue;
    bool ok = true;
    for (int i = 0; i < pdiv.size(); i++) {
      if (mpow(b, n / pdiv[i], n + 1) == 1) {
        ok = false;
        break;
      }
    }
    if (ok) {
      printf("%I64d\n", b);
      return 0;
    }
  }
  printf("-1\n");
}
