#include <bits/stdc++.h>
using namespace std;
const long long maxn = 100000 + 10;
long long m, s, prim[maxn], prime[maxn], yinm[maxn];
int pnum = 0, penum = 0, ynum = 0;
void prime1(long long x, long long p[], int& num) {
  num = 0;
  for (long long i = 2; i <= sqrt(x + 1); i++) {
    if (x % i == 0) {
      p[++num] = i;
      while (x % i == 0) x /= i;
    }
  }
  if (x != 1) p[++num] = x;
  sort(p + 1, p + num + 1);
}
void yin(long long x, long long p[], int& num) {
  num = 0;
  for (long long i = 1; i <= sqrt(x + 1); i++) {
    if (x % i == 0) {
      p[++num] = i;
      if (i * i != x) p[++num] = x / i;
    }
  }
  sort(p + 1, p + num + 1);
}
long long phi(long long x) {
  for (int i = 1; i <= pnum; i++)
    if (x % prim[i] == 0) x = x / prim[i] * (prim[i] - 1ll);
  return x;
}
long long mul(long long x, long long y, long long t) {
  long long m = (long long)((long double)(x)*y / t);
  long long ans = x * y - m * t;
  while (ans < 0) ans += t;
  while (ans >= t) ans -= t;
  return ans;
}
long long qpow(long long x, long long y, long long t) {
  x %= t;
  long long ans = 1;
  while (y) {
    if ((long long)y & 1) ans = mul(ans, x, t);
    y = (long long)y >> 1;
    x = mul(x, x, t);
  }
  return ans;
}
int main() {
  cin >> m >> s;
  prime1(m, prim, pnum);
  yin(m, yinm, ynum);
  long long e = phi(m), ans = 0;
  if (e > 1)
    prime1(e, prime, penum);
  else
    prime[++penum] = 1;
  for (int i = 1; i <= ynum; i++) {
    long long p = phi(yinm[i]), q = p;
    if (q > 1) {
      for (int j = 1; j <= penum; j++)
        while (q % prime[j] == 0 && qpow(s, q / prime[j], yinm[i]) == 1)
          q /= prime[j];
    }
    ans += p / q;
  }
  cout << ans << endl;
  return 0;
}
