#include <bits/stdc++.h>
#pragma comment(linker, "/stack:200000000")
#pragma GCC optimize("Ofast")
#pragma target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
using namespace std;
const int inf = 0x3f3f3f3f;
inline long long read() {
  register long long x = 0, f = 1;
  register char c = getchar();
  for (; !isdigit(c); c = getchar())
    if (c == '-') f = -1;
  for (; isdigit(c); c = getchar()) x = (x << 1) + (x << 3) + (c ^ 48);
  return x * f;
}
void write(long long x) {
  if (x < 0) x = -x, putchar('-');
  if (x >= 10) write(x / 10);
  putchar(x % 10 + '0');
}
void writeln(long long x) {
  write(x);
  puts("");
}
long long n, x, m, ans;
long long p[233], q[2333];
void d(long long x) {
  for (int i = 2; 1ll * i * i <= m; ++i)
    if (x % i == 0) {
      q[++*q] = i;
      while (x % i == 0) x /= i;
    }
  if (x > 1) q[++*q] = x;
}
long long times(long long x, long long y, long long mod) {
  long long res =
      (x * y - (long long)(((long double)x * y + 0.5) / mod) * mod) % mod;
  res = (res % mod + mod) % mod;
  return res;
}
long long qpow(long long a, long long b, long long mod) {
  long long ans = 1;
  for (; b; b >>= 1, a = times(a, a, mod))
    if (b & 1) ans = times(ans, a, mod);
  return ans;
}
long long phi(long long x) {
  long long res = x;
  for (register int i = (1); i <= int(*p); ++i)
    if (x % p[i] == 0) res = res / p[i] * (p[i] - 1);
  return res;
}
long long solve(long long a) {
  long long mod = n / a, t = phi(mod), tmp = t, xd = x % mod;
  for (int i = 1; i <= *q; ++i) {
    while (tmp % q[i] == 0 && qpow(xd, tmp / q[i], mod) == 1) tmp /= q[i];
  }
  return t / tmp;
}
int main() {
  n = read(), x = read(), m = n;
  for (int i = 2; 1ll * i * i <= m; ++i)
    if (m % i == 0) {
      p[++*p] = i;
      while (m % i == 0) m /= i;
    }
  if (m > 1) p[++*p] = m;
  for (register int i = (1); i <= int(*p); ++i) {
    q[++*q] = p[i];
    d(p[i] - 1);
  }
  sort(q + 1, q + 1 + *q);
  *q = unique(q + 1, q + 1 + *q) - q - 1;
  for (int i = 1; 1ll * i * i <= n; ++i) {
    if (n % i == 0) {
      ans += solve(i);
      if (n / i != i) ans += solve(n / i);
    }
  }
  writeln(ans);
  return 0;
}
