def Extended_Euclid(n,m): stack=[] while m: stack.append((n,m)) n,m=m,n%m if n>=0: x,y=1,0 else: x,y=-1,0 for i in range(len(stack)-1,-1,-1): n,m=stack[i] x,y=y,x-(n//m)*y return x,y P,Q=map(int,input().split()) X,Y=Extended_Euclid(P,Q) ans=0 for x,y in ((X,-Y),(-X,Y)): c=(1-y+Q-1)//Q x+=P*c y+=Q*c ans+=x+y print(ans)