import sys; input = sys.stdin.buffer.readline sys.setrecursionlimit(10**7) from collections import defaultdict con = 10 ** 9 + 7; INF = float("inf") from fractions import gcd def getlist(): return list(map(int, input().split())) # def gcd(a, b): # cnt = 0 # while b != 0: # a, b = b, a % b # cnt += 1 # return a #処理内容 def main(): M, N = getlist() GCD = gcd(M, N) M = int(M // GCD) N = int(N // GCD) ans = 0 up = M; down = N while up != 1 or down != 1: # print(up, down) if up < down: ans += 1 up, down = down, up else: if down == 1: ans += up - 1 break else: val = int((up - down) // down) + 1 ans += val up %= down # print(up, down) print(ans) if __name__ == '__main__': main()