#include <bits/stdc++.h>
using namespace std;
const long long INF = 1e18;
set<long long> s;
long long ans = 0, m;
long long gcd(long long a, long long b) { return b == 0 ? a : gcd(b, a % b); }
void getfactors(long long x) {
  s.clear();
  long long rx = sqrt(x);
  for (int i = 2; i <= rx; i++) {
    if (x % i == 0) {
      x /= i;
      s.insert(i);
      while (x % i == 0) x /= i;
    }
  }
  if (x > 1) s.insert(x);
}
int main() {
  long long x, y;
  scanf("%I64d%I64d", &x, &y);
  getfactors(x);
  while (y) {
    long long g = gcd(x, y);
    x /= g;
    y /= g;
    m = y;
    for (auto p : s)
      if (x % p == 0) m = min(m, y % p);
    ans += m;
    y -= m;
  }
  printf("%I64d\n", ans);
  return 0;
}
