#include <bits/stdc++.h>
using namespace std;
long long x, y;
long long gcd(long long a, long long b) {
  if (a % b == 0) return b;
  return gcd(b, a % b);
}
long long func(long long x, long long y) {
  if (!y) return 0;
  long long gc = gcd(x, y);
  x = x / gc;
  y = y / gc;
  long long tmpx = x, tmpy = y, tmp = y;
  for (long long i = 2; i * i <= x; i++) {
    if (x % i) continue;
    tmp = min(tmp, y % i);
    while (!(x % i)) x /= i;
  }
  if (x != 1) tmp = min(tmp, y % x);
  return func(tmpx, tmpy - tmp) + tmp;
}
int main() {
  cin >> x >> y;
  cout << func(x, y) << endl;
  return 0;
}
