#include <bits/stdc++.h>
using namespace std;
long long gcd(long long x, long long y) { return y == 0 ? x : gcd(y, x % y); }
vector<long long> primes(long long n) {
  vector<long long> ret;
  for (long long i = 2; i * i <= n; i++) {
    if (n % i == 0) {
      ret.push_back(i);
      while (n % i == 0) n /= i;
    }
  }
  if (n != 1) ret.push_back(n);
  return ret;
}
int main() {
  long long a, b;
  cin >> a >> b;
  long long ret = 0;
  while (b != 0) {
    long long g = gcd(a, b);
    a /= g;
    b /= g;
    long long next = 0;
    for (long long p : primes(a)) {
      next = max(next, (b - 1) / p * p);
    }
    ret += b - next;
    b = next;
  }
  cout << ret << endl;
}
