#include <bits/stdc++.h>
#pragma GCC optimize("O5")
using namespace std;
const long long maxn = 2e7 + 1000;
long long m, x;
long long pr[maxn], spr;
bool mark[maxn];
const long long lg = 12, base = (1 << lg) - 1;
inline long long mul(long long a, long long b, long long m) {
  if (b == 0) return 0;
  long long ans = ((b & base) * a) % m;
  ans = (ans + mul((a << lg) % m, b >> lg, m)) % m;
  return ans;
}
long long power(long long b, long long m) {
  long long a = x % m, ans = 1;
  while (b > 0ll) {
    if (b & 1ll) {
      ans = mul(ans, a, m);
    }
    a = mul(a, a, m);
    b >>= 1ll;
  }
  return ans;
}
void sieve() {
  for (long long i = 2; i < maxn; i++) {
    if (mark[i]) continue;
    pr[spr++] = i;
    for (long long j = i; j < maxn; j += i) {
      mark[j] = 1;
    }
  }
}
long long ans = 0;
void solve(long long m) {
  long long phi = m, s = m;
  for (long long i = 0; 1ll * pr[i] * pr[i] <= s; i++) {
    if (s % pr[i] == 0) {
      while (s % pr[i] == 0) {
        s /= pr[i];
      }
      phi -= phi / pr[i];
    }
  }
  if (s > 1) {
    phi -= phi / s;
  }
  long long d = phi, o = phi;
  for (long long i = 0; 1ll * pr[i] * pr[i] <= d; i++) {
    if (d % pr[i] == 0) {
      while (d % pr[i] == 0 && power(d / pr[i], m) == 1) {
        d /= pr[i];
      }
      while (o % pr[i] == 0) {
        o /= pr[i];
      }
    }
  }
  if (o > 1 && power(d / o, m) == 1) {
    d /= o;
  }
  ans += phi / d;
}
int32_t main() {
  sieve();
  scanf("%lld%lld", &m, &x);
  for (long long i = 1; i * i <= m; i++) {
    if (m % i == 0) {
      solve(m / i);
      if (i != m / i) {
        solve(i);
      }
    }
  }
  printf("%lld\n", ans);
}
