#include <bits/stdc++.h>
using namespace std;
long long gcd(long long a, long long b) { return a % b ? gcd(b, a % b) : b; }
bool isp[1000005];
vector<int> pl;
multiset<long long> ap;
int main() {
  isp[2] = true;
  for (int i = 3; i < 1000005; i += 2) isp[i] = true;
  for (int i = 3; i * i < 1000005; i += 2) {
    if (!isp[i]) continue;
    for (int j = i * i; j < 1000005; j += i) isp[j] = false;
  }
  pl.push_back(2);
  for (int i = 3; i < 1000005; i += 2)
    if (isp[i]) pl.push_back(i);
  long long x, y, ans = 0, g;
  scanf("%lld%lld", &x, &y);
  g = gcd(x, y);
  x /= g, y /= g;
  for (int i : pl) {
    if (1LL * i * i > x) break;
    while (x % i == 0) {
      x /= i;
      ap.insert(i);
    }
  }
  if (x > 1) ap.insert(x);
  while (y) {
    if (ap.empty()) {
      ans += y;
      break;
    }
    long long d = 1e18, ch = 0;
    for (long long i : ap) {
      long long t = y % i;
      if (t < d) d = t;
    }
    y -= d;
    ans += d;
    multiset<long long> nap;
    for (long long i : ap) {
      if (y % i == 0)
        y /= i;
      else
        nap.insert(i);
    }
    nap.swap(ap);
  }
  printf("%lld\n", ans);
}
