#int(input()) #map(int, input().split()) #list(map(int, input().split())) P, Q = map(int, input().split()) def xgcd(a,b): prevx, nextx = 1, 0 prevy, nexty = 0, 1 while b: quotient = a//b nextx, prevx = prevx - quotient * nextx, nextx nexty, prevy = prevy - quotient * nexty, nexty a, b = b, a % b # print(a,b) return prevx, prevy,a x, y, g = xgcd(P, -Q) a, b = divmod(x, Q) x -= Q * a y -= P * a mx = Q - x my = P - y print(x + y + mx + my)