#include <bits/stdc++.h>
using namespace std;
const long long mo = 100000000000031ll;
long long m, x, pri[50], ans;
int cnt[50];
long long divide(long long &a, long long b, bool fl) {
  if (b < 2 || a % b) return 1;
  long long ans = b - 1;
  if (fl == 0) cnt[++(*cnt)] = 1;
  for (a /= b; a % b == 0; a /= b)
    if (fl == 1)
      ans *= b;
    else
      cnt[*cnt]++;
  if (fl == 0) pri[*cnt] = b;
  return ans;
}
long long gcd(long long x, long long y) { return y ? gcd(y, x % y) : x; }
long long mul(long long x, long long y, long long mod) {
  long long ans = 0;
  for (; y; y >>= 16) {
    ans = (ans + x * (y & 65535)) % mod;
    x = (x << 16) % mod;
  }
  return ans;
}
long long power(long long x, long long y, long long mod) {
  long long ans = 1;
  for (; y; y /= 2, x = mul(x, x, mod))
    if (y & 1) ans = mul(ans, x, mod);
  return ans;
}
void dfs(int id, long long a, long long divi, long long phi) {
  if (id > *cnt) {
    ans = (ans + mul(gcd(m, power(x, a / divi, m) - 1), phi, mo)) % mo;
    return;
  }
  for (int j = 0; j <= cnt[id]; j++)
    dfs(id + 1, a, divi, phi), divi *= pri[id], phi *= pri[id] - (!j);
}
int main() {
  scanf("%lld%lld", &m, &x);
  long long a = m, b = divide(a, 2, 1) * divide(a, 3, 1);
  for (int i = 5; 1ll * i * i <= a; i += 6)
    b *= divide(a, i, 1) * divide(a, i + 2, 1);
  b *= divide(a, a, 1);
  a = b;
  divide(b, 2, 0);
  divide(b, 3, 0);
  for (int i = 5; 1ll * i * i <= b; i += 6)
    divide(b, i, 0), divide(b, i + 2, 0);
  divide(b, b, 0);
  dfs(1, a, 1, 1);
  ans = mul(ans, power(a, mo - 2, mo), mo);
  printf("%lld\n", ans);
}
