#include <bits/stdc++.h>
using namespace std;
inline long long read() {
  long long x = 0;
  char zf = 1;
  char ch = getchar();
  while (ch != '-' && !isdigit(ch)) ch = getchar();
  if (ch == '-') zf = -1, ch = getchar();
  while (isdigit(ch)) x = x * 10 + ch - '0', ch = getchar();
  return x * zf;
}
void write(long long y) {
  if (y < 0) putchar('-'), y = -y;
  if (y > 9) write(y / 10);
  putchar(y % 10 + 48);
}
void writeln(const long long y) {
  write(y);
  putchar('\n');
}
int i, j, k, m, n, x, y, z, cnt;
int q[10100], t;
void get(int x) {
  for (register int i = 2; i * i <= x && i != x; i++)
    if (x % i == 0) {
      q[++t] = i;
      if (i * i != x) q[++t] = x / i;
    }
}
long long ksm(long long x, long long y) {
  if (!y) return 1;
  long long ew = 1;
  while (y > 1) {
    if (y & 1) y--, ew = x * ew % n;
    y >>= 1, x = x * x % n;
  }
  return x * ew % n;
}
int main() {
  n = read();
  m = read();
  n++;
  for (register int i = 2; i * i <= n; i++)
    if (n % i == 0) {
      puts("-1");
      return 0;
    }
  get(n - 1);
  for (register int i = m - 1; i >= 2; i--) {
    x = i % n;
    if (!x) continue;
    bool tag = 1;
    for (register int j = 1; j <= t; j++)
      if (ksm(x, q[j]) == 1) {
        tag = 0;
        break;
      }
    if (tag == 1) {
      cout << i;
      return 0;
    }
  }
  cout << -1;
  return 0;
}
