from math import gcd def f(m, n): global ans if n == 1: ans += m - 1 return if m < n: ans += 1 return f(n, m) ans += m // n return f(m % n, n) M, N = map(int, input().split()) g = gcd(M, N) M //= g N //= g ans = 0 f(M, N) print(ans)