#include <bits/stdc++.h>
using namespace std;
void Get(int &T) {
  char C;
  bool F = 0;
  for (; C = getchar(), C < '0' || C > '9';)
    if (C == '-') F = 1;
  for (T = C - '0'; C = getchar(), C >= '0' && C <= '9'; T = T * 10 + C - '0')
    ;
  F && (T = -T);
}
int N, X;
void Init() {
  Get(N);
  Get(X);
  N++;
  X--;
}
long long Pow(long long A, long long B, long long Mod) {
  long long Ans = 1;
  A %= Mod;
  for (; B; B >>= 1) {
    if (B & 1) (Ans *= A) %= Mod;
    (A *= A) %= Mod;
  }
  return Ans;
}
int P[1005];
int Top;
void Work() {
  for (int k = 2; k * k <= N; k++)
    if (N % k == 0) {
      puts("-1");
      exit(0);
    }
  if (X == 1) {
    puts("-1");
    exit(0);
  }
  if (N == 2) {
    printf("%d\n", X);
    exit(0);
  }
  int R = N - 1;
  for (int i = 2; i * i <= R && R > 1; i++) {
    if (R % i == 0) {
      P[++Top] = (N - 1) / i;
      for (; R % i == 0;) R /= i;
    }
  }
  if (R > 1) P[++Top] = (N - 1) / R;
  for (int k = X; k >= 2; k--) {
    if (k % N != 0) {
      int p;
      for (p = 1; p <= Top; p++)
        if (Pow(k % N, P[p], N) == 1) break;
      if (p > Top) {
        printf("%d\n", k);
        exit(0);
      }
    }
  }
}
void Output() { puts("-1"); }
int main() {
  Init();
  Work();
  Output();
  return 0;
}
