#include <bits/stdc++.h>
using namespace std;
long long rdtsc() {
  long long tmp;
  asm("rdtsc" : "=A"(tmp));
  return tmp;
}
inline int myPower(int x, int p, int pw) {
  int res = 1;
  for (; pw; pw >>= 1) {
    if (pw & 1) res = (long long)res * x % p;
    x = (long long)x * x % p;
  }
  return res;
}
void getPrimes(int n, pair<int, int>* res, int& cnt) {
  cnt = 0;
  for (int p = 2; p * p <= n; p++) {
    if (n % p) continue;
    int countt = 0;
    while (!(n % p)) n /= p, countt++;
    res[cnt++] = make_pair(p, countt);
  }
  if (n > 1) res[cnt++] = make_pair(n, 1);
}
int isRoot(int x, int p, pair<int, int>* factors, int cnt) {
  for (int i = 0; i < cnt; i++) {
    int pw = (p - 1) / factors[i].first;
    if (myPower(x, p, pw) == 1) return 0;
  }
  return 1;
}
int gcd(int a, int b) { return b ? gcd(b, a % b) : a; }
const int maxn = 40;
pair<int, int> tmp[maxn];
int cnt;
inline bool isPrime(int x) {
  getPrimes(x, tmp, cnt);
  return tmp[0] == make_pair(x, 1);
}
int getB(int n, int x) {
  int p = n + 1;
  if (!isPrime(p)) return -1;
  getPrimes(n, tmp, cnt);
  int root = 1;
  while (!isRoot(root, p, tmp, cnt)) ++root;
  int ans = -1;
  for (int power = 0, val = 1; power < p - 1;
       power++, val = (long long)val * root % p) {
    if (gcd(power, p - 1) != 1) continue;
    if (val <= 1) val += p;
    if (x > val) ans = max(ans, val + (x - 1 - val) - (x - 1 - val) % p);
  }
  return ans;
}
bool solve() {
  int n, x;
  if (scanf("%d%d", &n, &x) < 2) return 0;
  printf("%d\n", getB(n, x));
  return 1;
}
int main() {
  srand(rdtsc());
  while (1) {
    if (!solve()) break;
  }
  return 0;
}
