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 return prevx, prevy # P/Q < Rp/Rq # P Rq < Rp Q # Rp Q - P Rq = できれば 1 # Lp/Lq < P/Q # P Lq - Q Lp = 1 # P Lq + Q (-Lp) # Rqをでかく! # Q Rp + P (-Rq) = 1 ans = 0 s,t = xgcd(q,p) if t<=-q: # t>-q にする # s-=p, t+=q # s-k*p, t+k*q (>-q) # t+k*q>-q # k*q>-q-t # k>(-q-t)/q # k>=(-t-1)//q k=(-t)//q s -= k*p t += k*q else: # t>-q の最大値 # s+=p, t-=q # s+k*p, t-k*q (>-q) # t-k*q>-q # k*q=q: #print("HERE") # t