#include <bits/stdc++.h>
using namespace std;
set<long long> s;
void getfac(long long x) {
  s.clear();
  long long fx = sqrt(x);
  for (int i = 2; i <= fx; i++) {
    if (x % i == 0) {
      x = x / i;
      s.insert(i);
      while (x % i == 0) x = x / i;
    }
  }
  if (x > 1) s.insert(x);
}
long long gcd(long long x, long long y) { return y == 0 ? x : gcd(y, x % y); }
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  long long n, m;
  while (cin >> n >> m) {
    long long ans = 0, cnt = 0;
    getfac(n);
    while (m) {
      long long g = gcd(n, m);
      n /= g;
      m /= g;
      cnt = m;
      for (auto x : s)
        if (n % x == 0) cnt = min(cnt, m % x);
      ans += cnt;
      m -= cnt;
    }
    cout << ans << endl;
  }
  return 0;
}
