#include <bits/stdc++.h>
using namespace std;
void check(long long int b, long long int p) {
  long long int prod = 1;
  for (int i = 1; i < p - 1; i++) {
    prod = (prod * b) % p;
    if (prod == 1) return;
  }
  cout << b << endl;
  exit(0);
}
int main() {
  long long int n, x;
  cin >> n >> x;
  long long int p = n + 1;
  for (int d = 2; d * d <= p; d++) {
    if (p % d == 0) {
      cout << -1 << endl;
      exit(0);
    }
  }
  for (int b = x - 1; b > 1; b--)
    if (b % p != 0) check(b, p);
  cout << -1 << endl;
}
