#include <bits/stdc++.h>
const int maxn = 107;
inline long long gcd(long long x, long long y) {
  return !y ? x : gcd(y, x % y);
}
inline long long times(long long a, long long b, long long P) {
  a %= P;
  b %= P;
  long long ret = 0;
  while (b) {
    if (b & 1) {
      ret += a;
      if (ret >= P) ret -= P;
    }
    a += a;
    if (a >= P) a -= P;
    b >>= 1;
  }
  return ret;
}
inline long long power(long long a, long long b, long long P) {
  a %= P;
  long long c = 1;
  for (; b; b >>= 1, a = times(a, a, P))
    if (b & 1) c = times(c, a, P);
  return c;
}
void findfac(long long v, long long res[], int &cnt) {
  for (long long i = 2; i * i <= v; ++i) {
    while ((v % i) == 0) {
      res[cnt++] = i;
      v /= i;
    }
  }
  if (v != 1) res[cnt++] = v;
}
long long M, X;
long long facm[maxn], facr[maxn][maxn];
int pm[maxn], pr[maxn], cntm = 0, cntr[maxn];
long long ans = 0;
void dfs(int p, long long u, long long phi, long long tp) {
  if (p == cntm) {
    if (u != 1) ans += phi / tp;
    return;
  }
  dfs(p + 1, u, phi, tp);
  if (u != 1) assert(power(X, tp, u) == 1);
  u *= facm[p];
  phi *= facm[p] - 1;
  long long tt = tp * (facm[p] - 1);
  for (int i = 0; i < cntr[p]; ++i) {
    if (power(X, tt / facr[p][i], u) == 1) tt /= facr[p][i];
  }
  dfs(p + 1, u, phi, tt);
  for (int i = 2; i <= pm[p]; ++i) {
    u *= facm[p];
    phi *= facm[p];
    if (power(X, tt, u) != 1) tt *= facm[p];
    dfs(p + 1, u, phi, tt);
  }
}
int main() {
  std::cin >> M >> X;
  assert(gcd(M, X) == 1);
  findfac(M, facm, cntm);
  std::sort(facm, facm + cntm);
  int t = 0;
  for (int i = 0; i < cntm; ++i) {
    if (i == 0 || facm[i] != facm[i - 1]) {
      facm[t++] = facm[i];
      pm[t - 1] = 1;
    } else {
      pm[t - 1]++;
    }
  }
  cntm = t;
  for (int i = 0; i < cntm; ++i) {
    findfac(facm[i] - 1, facr[i], cntr[i]);
    std::sort(facr[i], facr[i] + cntr[i]);
  }
  dfs(0, 1, 1, 1);
  ++ans;
  std::cout << ans << std::endl;
}
