#include <bits/stdc++.h>
using namespace std;
int a[100000 + 11], cnt, n, m, x;
inline long long quickpow(long long x, int y, int p) {
  long long rt;
  for (rt = 1; y; y >>= 1) {
    if (y & 1) rt = rt * x % p;
    x = x * x % p;
  }
  return rt;
}
inline bool isroot(int x) {
  for (int i = 1; i <= cnt; ++i)
    if (quickpow(x, a[i], m) == 1) return 0;
  return 1;
}
int main(int argc, char **argv) {
  scanf("%d%d", &n, &x);
  m = n + 1;
  for (int i = 2; i * i <= m; ++i)
    if (!(m % i)) {
      printf("-1\n");
      return 0;
    }
  for (int i = 2; i * i <= n; ++i)
    if (!(n % i)) a[++cnt] = i, a[++cnt] = n / i;
  for (--x; x > 1; --x)
    if (isroot(x % m)) break;
  printf("%d\n", x > 1 ? x : -1);
  return 0;
}
