#include <bits/stdc++.h>
using namespace std;
int ksm(int a, int k, int Mod) {
  int o = 1;
  for (; k > 0;) {
    if (k & 1) o = (int)((long long)o * a % Mod);
    a = (int)((long long)a * a % Mod);
    k >>= 1;
  }
  return o;
}
int main() {
  int n, x;
  scanf("%d%d", &n, &x);
  for (int i = 2; i * i <= n + 1; i++) {
    if ((n + 1) % i == 0) {
      puts("-1");
      return 0;
    }
  }
  for (int i = x - 1; i > 1; i--) {
    for (int j = 2; j * j <= n; j++)
      if (n % j == 0 && ksm(i, n / j, n + 1) == 1) goto Break;
    printf("%d\n", i);
    return 0;
  Break:;
  }
  puts("-1");
  return 0;
}
