#include <bits/stdc++.h>
using namespace std;
inline long long read() {
  long long neg = 1, num = 0;
  char c = getchar();
  for (; !isdigit(c); c = getchar())
    if (c == '-') neg = -1;
  for (; isdigit(c); c = getchar()) num = (num << 1) + (num << 3) + c - '0';
  return neg * num;
}
struct prime {
  long long tot, pri[100], cnt[100];
} M, A[100];
long long m, x, ans, p[1010], a[1010];
inline long long Mul(long long x, long long y, long long d) {
  long long sum = x * y - (long long)((long double)x * y / d + 0.5) * d;
  return sum < 0 ? sum + d : sum;
}
inline long long Pow(long long x, long long y, long long d) {
  long long sum = 1;
  for (; y; y >>= 1, x = Mul(x, x, d))
    if (y & 1) sum = Mul(sum, x, d);
  return sum;
}
inline void Init(prime &x, long long tmp, long long opt) {
  for (long long i = 2; i * i <= tmp; i++)
    if (tmp % i == 0) {
      x.pri[++x.tot] = i;
      while (tmp % i == 0) x.cnt[x.tot]++, tmp /= i;
      if (opt) Init(A[x.tot], i - 1, 0ll);
    }
  if (tmp != 1) {
    x.pri[++x.tot] = tmp;
    x.cnt[x.tot] = 1;
    if (opt) Init(A[x.tot], tmp - 1, 0ll);
  }
}
inline void Solve(long long d) {
  long long phi = 1, sum = 0, cnt = 0;
  for (long long i = 1; i <= M.tot; i++)
    if (d % M.pri[i] == 0) {
      long long tmp = d / M.pri[i];
      while (tmp % M.pri[i] == 0) p[++cnt] = M.pri[i], tmp /= M.pri[i];
      for (long long j = 1; j <= A[i].tot; j++)
        for (long long k = 1; k <= A[i].cnt[j]; k++) p[++cnt] = A[i].pri[j];
    }
  sort(p + 1, p + cnt + 1);
  sum = 0;
  for (long long i = 1; i <= cnt; i++) phi *= p[i], a[i] = 0;
  for (long long i = 1; i <= cnt; i++) {
    long long j = i;
    while (p[j + 1] == p[i] && j < cnt) j++;
    a[++sum] = j - i + 1;
    p[sum] = p[i];
    i = j;
  }
  cnt = sum;
  sum = 1;
  for (long long i = 1; i <= cnt; i++) {
    long long tmp = phi;
    for (long long j = 1; j <= a[i]; j++) {
      tmp /= p[i];
      if (Pow(x % d, tmp, d) != 1) break;
      sum = sum * p[i];
    }
  }
  ans += sum;
}
signed main() {
  m = read();
  x = read();
  Init(M, m, 1ll);
  for (long long i = 1; i * i <= m; i++)
    if (m % i == 0) {
      Solve(i);
      if (i * i != m) Solve(m / i);
    }
  printf("%lld", ans);
  return 0;
}
