#include <bits/stdc++.h>
using namespace std;
const int N = 100010;
long long gcd(long long a, long long b) {
  if (!b) return a;
  return gcd(b, a % b);
}
long long gcdExtended(long long a, long long b, long long *x, long long *y) {
  if (a == 0) {
    *x = 0;
    *y = 1;
    return b;
  }
  long long x1, y1;
  long long gcd = gcdExtended(b % a, a, &x1, &y1);
  *x = y1 - (b / a) * x1;
  *y = x1;
  return gcd;
}
long long mulmod(long long a, long long b, long long mod) {
  long long res = 0;
  a = a % mod;
  b = b % mod;
  while (b > 0) {
    if (b % 2 == 1) res = (res + a) % mod;
    a = (a * 2) % mod;
    b /= 2;
  }
  return res % mod;
}
int main(void) {
  long long x, y;
  cin >> x >> y;
  vector<long long> divisores;
  for (long long i = 1; i * i <= x; i++) {
    if (x % i == 0) {
      divisores.push_back(i);
      if (x / i != i) divisores.push_back(x / i);
    }
  }
  sort(divisores.begin(), divisores.end());
  int tam = divisores.size();
  long long g = gcd(x, y);
  long long sum = 0;
  while (y) {
    int pos = 0;
    for (int i = 0; i < tam; i++)
      if (divisores[i] == g) pos = i;
    long long at = divisores[pos];
    long long ans = LLONG_MAX;
    int nxt = -1;
    for (int i = pos + 1; i < tam; i++) {
      long long d = divisores[i];
      if (y % gcd(at, d)) continue;
      long long k, Q;
      if (d % at == 0) {
        k = (y / d) * d;
        k = (y - k) / at;
      } else {
        gcdExtended(at, d, &k, &Q);
        k = ((k % d) + d) % d;
        k = mulmod(k, y / gcd(at, d), d);
      }
      if (k <= ans) {
        ans = k;
        nxt = i;
      }
    }
    if (nxt == -1) {
      sum += y / at;
      break;
    }
    sum += ans;
    y = y - at * ans;
    g = gcd(x, y);
  }
  cout << sum << endl;
  return 0;
}
