#include <bits/stdc++.h>
using namespace std;
const int NMax = 1001000, MMax = 5100;
int N, X;
int POW(int a, int b, int m) {
  int ret = 1, tmp = a % m;
  while (b) {
    if (b & 1) {
      ret = ((long long)ret * tmp) % m;
      --b;
    }
    tmp = ((long long)tmp * tmp) % m;
    b >>= 1;
  }
  return ret;
}
int main() {
  scanf("%d%d", &N, &X);
  for (int i = 2; i <= (int)sqrt((double)(N + 1)); i++)
    if ((N + 1) % i == 0) {
      puts("-1");
      return 0;
    }
  for (int i = X - 1; i > 1; i--) {
    int flag = 1;
    for (int j = 2; j * j <= N; j++)
      if (N % j == 0) {
        if (POW(i, j, N + 1) == 1 || POW(i, N / j, N + 1) == 1) {
          flag = 0;
          break;
        }
      }
    if (flag) {
      printf("%d\n", i);
      return 0;
    }
  }
  puts("-1");
  return 0;
}
