#参考元 #https://tjkendev.github.io/procon-library/python/math/stern-brocot-tree.html def Stern_Brocot(p,q,n): a,b,c,d=0,1,1,0 lu,ru=1,1 lx,ly,rx,ry=0,1,1,0 flag=1 while flag and (lu or ru): flag=0 s=a+c; t=b+d if t*ps*q: flag=1 a,b=s,t if t<=n: lx,ly=s,t else: ru=0 return lx,ly,rx,ry #================================================== P,Q=map(int,input().split()) a,b,c,d=Stern_Brocot(P,Q,Q) print(a+b+c+d)