#include <bits/stdc++.h>
long long x, y, ans, d, mint, t, i;
long long gcd(long long a, long long b) {
  if (a % b == 0) return b;
  return gcd(b, a % b);
}
int main() {
  scanf("%lld%lld", &x, &y);
  ans = 0;
  while (y != 0) {
    d = gcd(x, y);
    if (d > 1) {
      x /= d;
      y /= d;
      y--;
      ans++;
    } else {
      if (x == 1) {
        ans += y;
        break;
      }
      mint = y;
      for (i = 2; i * i <= x; i++) {
        if (x % i != 0) continue;
        t = y % i;
        if (t < mint) mint = t;
        t = y % (x / i);
        if (t < mint) mint = t;
      }
      t = y % x;
      if (t < mint) mint = t;
      ans += mint;
      y -= mint;
      if (y == 0) break;
      d = gcd(x, y);
      x /= d;
      y /= d;
    }
  }
  printf("%lld\n", ans);
}
