#include <bits/stdc++.h>
using namespace std;
long long F[6000000];
long long n, x;
long long N, t, y, k1;
bool flag;
long long ans = 0;
long long gcd(long long x, long long y) {
  long long r;
  while (y % x) {
    r = y % x;
    y = x;
    x = r;
  }
  return x;
}
bool check(long long x) {
  for (long long i = 2; i <= sqrt(x); i++)
    if (x % i == 0) return false;
  return true;
}
bool c(long long i) {
  long long tmp = 1;
  long long v = i;
  while (v != 1LL) {
    tmp++;
    v = v * i % N;
  }
  if (tmp == N - 1LL)
    return true;
  else
    return false;
}
void pre() {
  for (long long i = 2; i < N; i++) {
    if (c(i)) {
      t = i;
      break;
    }
  }
}
void solve() {
  for (long long i = 1; i < N; i++) {
    if (gcd(i, N - 1LL) == 1LL) {
      y = F[i];
      if (x >= y) {
        k1 = (x - y) / N;
        ans = max(ans, k1 * N + y);
      }
    }
  }
}
int main() {
  while (~scanf("%I64d%I64d", &n, &x)) {
    x--;
    if (x == 1) {
      printf("-1\n");
      continue;
    }
    N = n + 1LL;
    flag = false;
    ans = 0;
    memset(F, 0, sizeof(F));
    if (check(N)) {
      pre();
      if (N == 2) t = 1;
      F[1] = t;
      for (long long i = 2; i < N; i++) F[i] = F[i - 1] * t % N;
      solve();
      if (ans != 0)
        printf("%I64d\n", ans);
      else
        printf("-1\n");
    } else
      printf("-1\n");
  }
  return 0;
}
