#include <bits/stdc++.h>
using namespace std;
vector<int> factors(int x) {
  vector<int> res;
  for (int i = 2; i <= x; ++i) {
    if (x % i == 0) {
      res.push_back(i);
    }
    while (x % i == 0) {
      x /= i;
    }
  }
  return res;
}
vector<int> f;
int p;
int pot(int a, int b) {
  int res = 1;
  for (; b > 0; b >>= 1) {
    if (b & 1) {
      res = (res * (long long)a) % p;
    }
    a = (a * (long long)a) % p;
  }
  return res;
}
bool check(int x) {
  if (x < 2 || x > p - 1) {
    return false;
  }
  for (__typeof(f.begin()) it = (f.begin()); it != (f).end(); ++it) {
    if (pot(x, (p - 1) / *it) == 1) {
      return false;
    }
  }
  return true;
}
int gcd(int a, int b) {
  while (a && b) {
    a > b ? a %= b : b %= a;
  }
  return a + b;
}
int main() {
  ios_base::sync_with_stdio(false);
  int n, x;
  cin >> n >> x;
  if (x == 2) {
    cout << -1 << endl;
    return 0;
  }
  if (n == 1) {
    cout << x - 1 << endl;
    return 0;
  }
  if (factors(n + 1)[0] != n + 1) {
    cout << -1 << endl;
    return 0;
  }
  p = n + 1;
  f = factors(n);
  int g = 1;
  while (!check(g)) {
    g = rand() % p;
  }
  int res = -1;
  int c = 1;
  for (int i = 1; i < p; ++i) {
    c = (c * (long long)g) % p;
    if (gcd(p - 1, i) == 1) {
      if (x > c) {
        res = max(res, c + ((x - c - 1) / p) * p);
      }
    }
  }
  cout << res << endl;
}
