#include <bits/stdc++.h>
using namespace std;
void vaild_prime(long long x, long long vp[], int &cnt) {
  cnt = 0;
  for (long long i = 2; i * i <= x; i++)
    if (x % i == 0) {
      vp[++cnt] = i;
      while (x % i == 0) x /= i;
    }
  if (x != 1) vp[++cnt] = x;
  sort(vp + 1, vp + cnt + 1);
}
void vaild_factor(long long x, long long ft[], int &cnt) {
  cnt = 0;
  for (long long i = 1; i * i <= x; i++)
    if (x % i == 0) {
      ft[++cnt] = i;
      if (i * i != x) ft[++cnt] = x / i;
    }
  sort(ft + 1, ft + cnt + 1);
}
long long mul(long long x, long long y, long long MOD) {
  long long res = (x * y - (long long)((double)x * y / MOD + 0.1) * MOD) % MOD;
  if (res < 0) res += MOD;
  return res;
}
long long fst_pow(long long a, long long b, long long MOD) {
  long long res = 1;
  a %= MOD;
  while (b) {
    if (b & 1LL) res = mul(res, a, MOD);
    a = mul(a, a, MOD);
    b >>= 1LL;
  }
  return res;
}
long long m, x;
long long vp[100000 + 5], ft[100000 + 5], pp[100000 + 1];
int ct1, ct2, ct3;
long long phi(long long x) {
  for (int i = 1; i <= ct1; i++)
    if (x % vp[i] == 0) x = x / vp[i] * (vp[i] - 1);
  return x;
}
int main() {
  scanf("%lld%lld", &m, &x);
  vaild_factor(m, ft, ct2);
  vaild_prime(m, vp, ct1);
  long long Ph = phi(m), ans = 0;
  if (Ph > 1)
    vaild_prime(Ph, pp, ct3);
  else
    pp[++ct3] = 1;
  for (int i = 1; i <= ct2; i++) {
    long long f = phi(ft[i]), l = f;
    if (l > 1) {
      for (int j = 1; j <= ct3; j++)
        while (l % pp[j] == 0 && fst_pow(x, l / pp[j], ft[i]) == 1) l /= pp[j];
    }
    ans += f / l;
  }
  printf("%lld", ans);
}
