from math import gcd import sys input = sys.stdin.readline P, Q = map(int, input().split()) def calc(p, q): while True: np, nq = p*Q+P*q, 2*q*Q g = gcd(np, nq) np //= g nq //= g if nq < Q: p, q = np, nq else: break return p, q pl, ql = calc(1, Q) pr, qr = calc(1, 1) print(pl+ql+pr+qr)