"""faray数列?""" def extgcd(a, b): """ 拡張Euclidの互除法 INPUT: a, b OUTPUT: d: gcd(a, b) (x, y): ax + by = d の解 """ if b == 0: return a, (1, 0) d, (y, x) = extgcd(b, a % b) y -= a // b * x return d, (x, y) P, Q = map(int, input().split()) d, (x, y) = extgcd(P, -Q) if d == -1: x = -x y = -y x %= Q y %= P dd, (xx, yy) = extgcd(Q, -P) if dd == -1: xx = -xx yy = -yy xx %= P yy %= Q print(x + y + xx + yy)