#include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,fma")
#pragma GCC optimize("unroll-loops")
using namespace std;
const double eps = 1e-10, pi = 3.1415926535898;
const int mod = 1e9 + 7, maxn = 2e4 + 10;
int ind, inp;
long long n, m, k, x, y, ans;
vector<long long> v;
stack<long long> s;
struct P {
  long long x, y;
} p[maxn], pp[maxn];
vector<P> vp;
long long get_euler(long long n) {
  long long cnt = 1;
  for (long long i = 2; i * i <= n; ++i) {
    if (n % i) continue;
    n /= i;
    long long x = i - 1;
    y = 1;
    while (n % i == 0) {
      n /= i;
      x *= i;
      ++y;
    }
    cnt *= x;
    vp.push_back({i, y});
  }
  if (n > 1) {
    cnt *= n - 1;
    vp.push_back({n, 1});
  }
  return cnt;
}
long long mul(long long x, long long k, long long mod) {
  long long cnt = 0;
  x %= mod;
  while (k) {
    if (k & 1) cnt += x;
    if (cnt >= mod) cnt -= mod;
    x *= 2;
    if (x >= mod) x -= mod;
    k >>= 1;
  }
  return cnt;
}
long long qpow(long long x, long long k, long long mod) {
  long long cnt = 1;
  while (k) {
    if (k & 1) cnt = mul(cnt, x, mod);
    x = mul(x, x, mod);
    k >>= 1;
  }
  return cnt;
}
void dfs(int q) {
  if (q == ind) {
    long long cnt = m, z = 1;
    for (int i = 0; i < ind; ++i) {
      if (p[i].y == 0) {
        cnt /= p[i].x - 1;
        for (int j = 2; j <= vp[i].y; ++j) {
          cnt /= p[i].x;
        }
      } else {
        for (int j = vp[i].y; j > p[i].y; --j) {
          cnt /= p[i].x;
        }
      }
      for (int j = 1; j <= p[i].y; ++j) {
        z *= p[i].x;
      }
    }
    z = n / z;
    if (z == n) {
      ++ans;
      return;
    }
    y = 0;
    for (int j = 1; j <= inp; ++j) {
      y = pp[j].x;
      if (pp[j].y % (n / z) == 1) {
        break;
      }
    }
    ans += cnt / y;
    return;
  }
  for (int i = 0; i <= vp[q].y; ++i) {
    p[q] = {vp[q].x, i};
    dfs(q + 1);
  }
  return;
}
int main(int argc, char const *argv[]) {
  scanf("%lld %lld", &n, &x);
  m = get_euler(n);
  ind = vp.size();
  for (long long i = 1; i * i <= m; ++i) {
    if (m % i == 0) {
      v.push_back(i);
      if (i * i < m) {
        s.push(m / i);
      }
    }
  }
  while (!s.empty()) {
    v.push_back(s.top());
    s.pop();
  }
  for (long long i : v) {
    pp[++inp] = {i, qpow(x, i, n)};
  }
  dfs(0);
  printf("%lld\n", ans);
  return 0;
}
