#include <bits/stdc++.h>
using namespace std;
long long x, y, tmp, factor, x2, ans = 0, high_y, high_factor;
set<long long> s;
set<long long>::iterator it;
long long gcd(long long a, long long b) { return b == 0 ? a : gcd(b, a % b); }
int main() {
  scanf("%I64d %I64d", &x, &y);
  tmp = gcd(x, y);
  x /= tmp;
  y /= tmp;
  x2 = x;
  while (x2 > 1 && x2 % 2 == 0) {
    s.insert(2);
    x2 /= 2;
  }
  factor = 3;
  while (x2 > 1) {
    if (factor * factor > x2) factor = x2;
    if (x2 % factor == 0) {
      s.insert(factor);
      x2 /= factor;
    } else
      factor += 2;
  }
  while (y > 0) {
    high_y = 0;
    high_factor = 1;
    for (it = s.begin(); it != s.end(); it++) {
      if (high_y < y / (*it) * (*it)) {
        high_y = y / (*it) * (*it);
        high_factor = *it;
      }
    }
    ans += y - high_y;
    x /= high_factor;
    y = high_y / high_factor;
    if (x % high_factor != 0) s.erase(high_factor);
  }
  printf("%I64d\n", ans);
  return 0;
}
