import sys #input = sys.stdin.readline input = sys.stdin.buffer.readline #文字列はダメ #sys.setrecursionlimit(1000000) #import bisect #import itertools #import random #from heapq import heapify, heappop, heappush #from collections import defaultdict #from collections import deque #import copy #import math #from functools import lru_cache #@lru_cache(maxsize=None) #MOD = pow(10,9) + 7 #MOD = 998244353 #dx = [1,0,-1,0] #dy = [0,1,0,-1] #dx8 = [1,1,0,-1,-1,-1,0,1] #dy8 = [0,1,1,1,0,-1,-1,-1] def calc(X): n = len(X) for i in reversed(range(n-1)): if i == n-2: a = X[i] b = X[i+1] c = 1 else: a = X[i] nc = b nb = a*b + c b,c = nb,nc #print(b,c) return b,c def main(): P,Q = map(int,input().split()) A = [0] while True: print(P,Q) v = Q // P if P == 1: #print("last",A) if Q != 1: A.append(Q-1) A.append(1) break A.append(v) q = Q; p = P P = q - p*v Q = p #print(A) P0,Q0 = calc(A[:-1]) P1,Q1 = calc(A[:-2]) ans = P0 + Q0 + P1 + Q1 print(ans) if __name__ == '__main__': main()