#include <bits/stdc++.h>
using namespace std;
bool IsPrime(int x) {
  for (int i = 2; i * i <= x; i++)
    if (x % i == 0) return false;
  return true;
}
int modpow(int w, int p, int m) {
  if (p == 0) return 1;
  int x = modpow(w, p / 2, m);
  x = 1LL * x * x % m;
  if (p & 1) x = 1LL * x * w % m;
  return x;
}
int main() {
  int L, x, p;
  scanf("%d%d", &L, &x);
  p = L + 1;
  if ((x == 2) || !IsPrime(p)) {
    puts("-1");
    return 0;
  }
  if (L == 1) {
    printf("%d\n", x - 1);
    return 0;
  }
  for (int b = x - 1; b > 1; b--) {
    if (modpow(b, L, p) != 1) continue;
    if (b % p == 0) continue;
    long long t = 0, r = 1, n = 0, x, d;
    while (1) {
      t = t + 1;
      x = r * b;
      d = x / p;
      r = x % p;
      n = n * b + d;
      if (r == 1) break;
      if (t > p / 2) {
        printf("%d\n", b);
        return 0;
      }
    }
    if (t == L) {
      printf("%d\n", b);
      return 0;
    }
  }
  puts("-1");
  return 0;
}
