#include <bits/stdc++.h>
using namespace std;
const int MAXN = 100000 + 10;
int n, prime[MAXN], tot, first;
int Pow(int a, int b, int n) {
  int d = 1;
  for (; b;
       d = (b & 1) ? (long long)d * a % n : d, a = (long long)a * a % n, b /= 2)
    ;
  return d;
}
bool check(int first) {
  first %= n + 1;
  for (int i = 1; i <= tot; ++i)
    if (Pow(first, n / prime[i], n + 1) == 1) return false;
  return true;
}
int main() {
  cin >> n >> first;
  for (int i = 2, tmp = n + 1; i * i <= tmp; ++i)
    if (tmp % i == 0) puts("-1"), exit(0);
  int xx = n;
  for (int i = 2; i * i <= xx; ++i)
    if (xx % i == 0) {
      prime[++tot] = i;
      for (; xx % i == 0; xx /= i)
        ;
    }
  if (xx > 1) prime[++tot] = xx;
  for (--first; !check(first); --first)
    ;
  if (first <= 1)
    puts("-1");
  else
    printf("%d\n", first);
  fclose(stdin);
  fclose(stdout);
  return 0;
}
