#include <bits/stdc++.h>
using namespace std;
const long long Base = 1e4;
map<long long, vector<pair<long long, int> > > mp;
vector<pair<long long, int> > vec, vec2, vec3;
long long ans, m, x;
inline void Zarb(long long &a, long long b, long long c) {
  long long A = a * (b % Base);
  b /= Base;
  long long B = a * (b % Base) % c * Base;
  b /= Base;
  long long C = a * (b % Base) % c * Base % c * Base;
  b /= Base;
  long long D = a * (b % Base) % c * Base % c * Base % c * Base;
  b /= Base;
  long long E = a * (b % Base) % c * Base % c * Base % c * Base % c * Base;
  a = (A + B + C + D + E) % c;
}
long long tavan(long long a, long long b, long long md) {
  long long ans = 1;
  while (b) {
    if (b & 1) Zarb(ans, a, md);
    Zarb(a, a, md);
    b /= 2;
  }
  return ans;
}
void go(int nw = 0, long long num = 1) {
  if (nw == int((vec).size())) {
    long long Phi = num, Ord = 0, w = 1;
    vec2.clear();
    vec3.clear();
    for (int i = 0; i < int((vec).size()); i++) {
      if (vec[i].second == 0) continue;
      if (vec[i].second > 1) vec2.push_back({vec[i].first, vec[i].second - 1});
      Phi /= vec[i].first;
      for (auto PP : mp[vec[i].first - 1]) vec2.push_back(PP);
      w *= vec[i].first - 1;
    }
    Phi *= w;
    Ord = Phi;
    sort(vec2.begin(), vec2.end());
    for (int i = 0; i < int((vec2).size()); i++) {
      if (i + 1 == int((vec2).size()) || vec2[i].first != vec2[i + 1].first)
        vec3.push_back(vec2[i]);
      else
        vec2[i + 1].second += vec2[i].second;
    }
    for (auto PP : vec3) {
      while (PP.second && tavan(x, Ord, num) == 1) PP.second--, Ord /= PP.first;
      if (tavan(x, Ord, num) != 1) Ord *= PP.first;
    }
    ans += Phi / Ord;
    return;
  }
  int N = vec[nw].second;
  for (int i = 0; i <= N; i++) {
    vec[nw].second = i;
    go(nw + 1, num);
    num *= vec[nw].first;
  }
  vec[nw].second = N;
}
void tajzie(long long x, vector<pair<long long, int> > &vec) {
  for (long long p = 2; (p * p) <= x; p++) {
    if (x % p == 0) {
      int cnt = 0;
      while (x % p == 0) x /= p, cnt++;
      vec.push_back({p, cnt});
    }
  }
  if (x > 1) vec.push_back({x, 1});
}
int main() {
  cin >> m >> x;
  tajzie(m, vec);
  for (auto PP : vec) tajzie(PP.first - 1, mp[PP.first - 1]);
  go();
  cout << ans << endl;
  return 0;
}
