#include <bits/stdc++.h>
using namespace std;
int R[10000000];
int N[10000000];
bool A[10000000];
int main(void) {
  int n, x;
  int i, k;
  cin >> n >> x;
  int p = n + 1;
  k = sqrt((double)(p + 1));
  for (i = 2; i <= k && p % i; i++)
    ;
  if (n == 1)
    cout << x - 1;
  else if (i <= k) {
    cout << -1;
  } else {
    fill(R, R + p, 0);
    for (i = 2; i < p; i++) {
      if (R[i] == 0) {
        k = 1;
        for (long long t = i; t != 1; k++, t = (t * i) % p) R[t] = i, N[t] = k;
        if (k == p - 1) break;
      }
    }
    if (i == p)
      cout << -1;
    else {
      fill(A, A + p, true);
      for (k = 2; k < p; ++k) {
        if (n % k == 0) {
          for (int t = k; t < p; t += k) A[t] = false;
        }
      }
      int res = -1;
      for (i = 2; i < p; i++)
        if (A[N[i]] && i < x) {
          int v = ((x - 1 - i) / p) * p + i;
          if (v > res) res = v;
        }
      cout << res;
    }
  }
  return 0;
}
