#include <bits/stdc++.h>
using namespace std;
const int N = 10000010;
bool vis[N];
int prime[N], tot;
void get(int n) {
  for (int i = 2; i <= n; i++) {
    if (!vis[i]) {
      prime[++tot] = i;
    }
    for (int j = 1; j <= tot && i * prime[j] <= n; j++) {
      vis[i * prime[j]] = 1;
      if (i % prime[j] == 0) {
        break;
      }
    }
  }
}
long long multi(long long x, long long y, long long mod) {
  long long ret = 0;
  for (; y; y >>= 1, x = (x << 1) % mod) {
    if (y & 1) {
      ret = (ret + x) % mod;
    }
  }
  return ret % mod;
}
long long power(long long x, long long y, long long mod) {
  long long ret = 1;
  if (mod <= 3e9) {
    for (; y; y >>= 1, x = x * x % mod) {
      if (y & 1) {
        ret = ret * x % mod;
      }
    }
  } else {
    for (; y; y >>= 1, x = multi(x, x, mod)) {
      if (y & 1) {
        ret = multi(ret, x, mod);
      }
    }
  }
  return ret % mod;
}
vector<long long> p, q, h, g;
long long ans;
void dfs(int k, long long now, long long phi_now) {
  if (k == p.size()) {
    for (int i = 0; i < h.size(); i++) {
      if (g[i] % now == 1 && phi_now % h[i] == 0) {
        ans += phi_now / h[i];
        return;
      }
    }
    return;
  }
  dfs(k + 1, now, phi_now);
  now *= p[k];
  phi_now *= (p[k] - 1);
  for (int i = 0; i < q[k]; i++) {
    dfs(k + 1, now, phi_now);
    now *= p[k];
    phi_now *= p[k];
  }
}
int main() {
  get(1e7);
  long long m, x;
  cin >> m >> x;
  long long tmp = m, phi_m = m;
  for (int i = 1; i <= tot; i++) {
    int x = prime[i];
    if (tmp % x == 0) {
      int k = 0;
      while (tmp % x == 0) {
        tmp /= x;
        k++;
      }
      p.push_back(x);
      q.push_back(k);
      phi_m = phi_m / x * (x - 1);
    }
  }
  if (tmp != 1) {
    p.push_back(tmp);
    q.push_back(1);
    phi_m = phi_m / tmp * (tmp - 1);
  }
  long long lim = sqrt(phi_m);
  for (int i = 1; i <= lim; i++) {
    if (phi_m % i == 0) {
      h.push_back(i);
      if (phi_m / i != i) {
        h.push_back(phi_m / i);
      }
    }
  }
  sort(h.begin(), h.end());
  for (int i = 0; i < h.size(); i++) {
    g.push_back(power(x, h[i], m));
  }
  dfs(0, 1, 1);
  cout << ans + 1 << endl;
  return 0;
}
