#include <bits/stdc++.h>
using namespace std;
const int N = 5010;
const int inf = 0x3f3f3f3f;
int n, x;
bool is_prim(int x) {
  for (int i = 2; i * i <= x; i++)
    if (x % i == 0) return 0;
  return 1;
}
long long pow(long long a, long long b, long long mod) {
  long long ret = 1;
  while (b) {
    if (b & 1) ret = ret * a % mod;
    a = a * a % mod;
    b >>= 1;
  }
  return ret;
}
int main() {
  cin >> n >> x;
  if (x == 1 || !is_prim(n + 1))
    ;
  else {
    for (int b = x - 1; b > 1; b--) {
      bool f = 1;
      for (int i = 2; i * i <= n; i++) {
        if (n % i) continue;
        if (pow(b, i, n + 1) == 1) f = 0;
        if (pow(b, n / i, n + 1) == 1) f = 0;
        if (f == 0) break;
      }
      if (f) return printf("%d\n", b), 0;
    }
  }
  puts("-1");
  return 0;
}
