#include <bits/stdc++.h>
using namespace std;
void factor(long long m, vector<long long>& factors,
            vector<long long>& divisors) {
  long long r = m;
  divisors.push_back(m);
  for (long long i = 2; i * i <= m; i++) {
    if (m % i) continue;
    divisors.push_back(i);
    if (i * i != m) {
      divisors.push_back(m / i);
    }
    if (r % i == 0) {
      factors.push_back(i);
      while (r % i == 0) {
        r /= i;
      }
    }
  }
  if (r > 1) factors.push_back(r);
}
long long mul(long long a, long long p, long long m) {
  long long r = 0;
  while (p) {
    if (p & 1) {
      r = r + a;
      if (r >= m) r -= m;
    }
    a = a + a;
    if (a >= m) a -= m;
    p >>= 1;
  }
  return r;
}
long long bin_pow(long long a, long long p, long long m) {
  long long r = 1;
  while (p) {
    if (p & 1) {
      r = mul(r, a, m);
    }
    a = mul(a, a, m);
    p >>= 1;
  }
  return r;
}
long long solve(vector<long long>& factors, vector<long long>& phi_factors,
                long long d, long long x) {
  x %= d;
  long long phi = 1, r = d;
  for (long long f : factors) {
    if (r % f) continue;
    r /= f;
    phi *= f - 1;
    while (r % f == 0) {
      r /= f;
      phi *= f;
    }
  }
  assert(r == 1);
  assert(bin_pow(x, phi, d) == 1);
  long long order = phi;
  for (long long f : phi_factors) {
    while (order % f == 0 && bin_pow(x, order / f, d) == 1) {
      order /= f;
    }
  }
  return phi / order;
}
vector<long long> m1factors(vector<long long>& factors) {
  vector<long long> phi_factors = factors;
  for (long long f : factors) {
    f--;
    for (long long i = 2; i * i <= f; i++) {
      if (f % i == 0) {
        phi_factors.push_back(i);
        while (f % i == 0) f /= i;
      }
    }
    if (f > 1) phi_factors.push_back(f);
  }
  phi_factors.resize(unique(phi_factors.begin(), phi_factors.end()) -
                     phi_factors.begin());
  return phi_factors;
}
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  long long m, x;
  cin >> m >> x;
  vector<long long> factors, divisors;
  factor(m, factors, divisors);
  vector<long long> phi_factors = m1factors(factors);
  long long ans = 1;
  for (long long d : divisors) {
    ans += solve(factors, phi_factors, d, x);
  }
  cout << ans << endl;
}
