#include <bits/stdc++.h>
using namespace std;
const int N = 5000005;
int n, x;
bool check(int x, int y, int mod) {
  int cur = 1;
  for (int i = 29; i >= 0; i--) {
    cur = (long long)cur * cur % mod;
    if (y & 1 << i) cur = (long long)cur * x % mod;
  }
  return cur == 1;
}
int main() {
  scanf("%d%d", &n, &x);
  for (int i = 2; i * i <= n + 1; i++)
    if ((n + 1) % i == 0) return puts("-1"), 0;
  for (int i = x - 1; i >= 2; i--) {
    bool flag = 0;
    for (int j = 2; j * j <= n; j++)
      if (n % j == 0 && check(i, n / j, n + 1)) {
        flag = 1;
        break;
      }
    if (!flag) return printf("%d\n", i), 0;
  }
  puts("-1");
  return 0;
}
