#include <bits/stdc++.h>
using namespace std;
const long long Inf = 1000000000000000000ll;
const int inf = 1000000000;
vector<long long> pri, fac;
long long m, x, ans;
void getpri(long long t, vector<long long>& v) {
  v.clear();
  for (long long i = 2; i * i <= t; ++i) {
    if (t % i) continue;
    v.push_back(i);
    while (t % i == 0) t /= i;
  }
  if (t != 1) v.push_back(t);
  sort(v.begin(), v.end());
}
long long Euler(long long t) {
  long long res = t;
  for (int i = 0; i < pri.size(); ++i)
    if (t % pri[i] == 0) res = res / pri[i] * (pri[i] - 1);
  return res;
}
long long mul(long long x, long long y, long long mod) {
  long long res = 0;
  while (y) {
    if (y & 1) (res += x) >= mod && (res -= mod);
    (x <<= 1) >= mod && (x -= mod);
    y >>= 1ll;
  }
  return res;
}
long long qpow(long long b, long long p, long long mod) {
  long long res = 1ll;
  b %= mod;
  while (p) {
    if (p & 1ll) res = mul(b, res, mod);
    b = mul(b, b, mod);
    p >>= 1ll;
  }
  return res;
}
void work(long long md) {
  long long f_d = Euler(md);
  long long l_d = f_d;
  if (l_d > 1) {
    for (int j = 0; j < fac.size(); ++j)
      while (l_d % fac[j] == 0 && qpow(x, l_d / fac[j], md) == 1) l_d /= fac[j];
  }
  ans += f_d / l_d;
}
int main() {
  scanf("%lld%lld", &m, &x);
  getpri(m, pri);
  long long eul = Euler(m);
  if (eul > 1)
    getpri(eul, fac);
  else
    fac.push_back(1);
  for (long long i = 1; i * i <= m; ++i) {
    if (m % i) continue;
    work(i);
    if (i * i != m) work(m / i);
  }
  printf("%lld\n", ans);
  return 0;
}
