import sys
sys.setrecursionlimit(1000000)

def inpl(): return list(map(int, input().split()))
N, X = map(int, input().split())

def calc(A, B, i):
    d, m = divmod(A, B)
    if m == 0:
        tmp = (2*d-(i%3 > 0))*B
        return tmp
    else:
        tmp = (2*d+1-i)*B
        tmp += calc(B, m, (i+1)%3)
        return tmp
ans = calc(X, N-X, 0) + X
print(ans)
