#include <bits/stdc++.h>
using namespace std;
long long read() {
  long long a = 0, b = getchar(), c = 1;
  while (!isdigit(b)) c = b == '-' ? -1 : 1, b = getchar();
  while (isdigit(b)) a = a * 10 + b - '0', b = getchar();
  return a * c;
}
long long x, y;
long long gcd(long long x, long long y) {
  if (x % y == 0) return y;
  return gcd(y, x % y);
}
long long gg(long long x, long long y) {
  if (!y) return 0;
  long long gc = gcd(x, y);
  x = x / gc, y = y / gc;
  long long rx = x, ry = y, r = y;
  for (long long i = 2; i * i <= x; i++) {
    if (x % i) continue;
    r = min(r, y % i);
    while (!(x % i)) x /= i;
  }
  if (x != 1) r = min(r, y % x);
  return gg(rx, ry - r) + r;
}
int main() {
  x = read(), y = read();
  printf("%lld", gg(x, y));
  return 0;
}
