#include <bits/stdc++.h>
long long m, x, ans;
long long mul(long long x, long long y, long long mod) {
  long long ret = x * y - (long long)((long double)x * y / mod + 0.5) * mod;
  return ret + (ret >> 63 & mod);
}
long long pow(long long x, long long y, long long mod, long long ans = 1) {
  for (; y; y >>= 1, x = mul(x, x, mod))
    if (y & 1) ans = mul(ans, x, mod);
  return ans;
}
long long primes[60];
int tot, qaq, expo[60];
void factor(long long n, int &tot) {
  auto check = [&](long long x) {
    if (n % x == 0) {
      primes[tot] = x;
      do ++expo[tot];
      while ((n /= x) % x == 0);
      ++tot;
    }
  };
  check(2);
  check(3);
  for (int i = 5, t = 2; (long long)i * i <= n; i += t, t = 6 - t) check(i);
  if (n > 1) check(n);
}
long long solve(long long val, long long phi) {
  if (val == 1) return 1;
  for (int i = tot; i < qaq; ++i)
    while (phi % primes[i] == 0 && pow(x % val, phi / primes[i], val) == 1)
      phi /= primes[i];
  return phi;
}
void dfs(int dep, long long val, long long phi) {
  if (dep == tot) {
    ans += phi / solve(val, phi);
    return;
  }
  dfs(dep + 1, val, phi);
  for (int i = 0; i < expo[dep]; ++i)
    dfs(dep + 1, val *= primes[dep], phi *= (primes[dep] - (i == 0)));
}
int main() {
  std::ios::sync_with_stdio(0), std::cin.tie(0);
  std::cin >> m >> x, factor(m, tot), qaq = tot;
  long long phi = m;
  for (int i = 0; i < tot; ++i) phi /= primes[i], phi *= primes[i] - 1;
  factor(phi, qaq);
  dfs(0, 1, 1), std::cout << ans << '\n';
  return 0;
}
