#include <bits/stdc++.h>
using namespace std;
long long n, x;
int main() {
  cin >> n >> x;
  if (x == 2) {
    puts("-1");
    return 0;
  }
  if (n == 1) {
    cout << x - 1 << endl;
    return 0;
  }
  long long p = n + 1;
  bool bad = false;
  for (int i = 2; i * i <= p; i++)
    if (p % i == 0) {
      bad = true;
      break;
    }
  if (bad) {
    puts("-1");
    return 0;
  }
  long long res = -1;
  int cnt = 0;
  for (long long b = x - 1; b > 1 && cnt < 100000000; b--) {
    if (b % p == 0) continue;
    long long t = 0, r = 1;
    while (1) {
      t++;
      r = (r * b) % p;
      if (r == 1) break;
      cnt++;
    }
    if (t != p - 1) continue;
    res = b;
    break;
  }
  cout << res << endl;
  return 0;
}
