#!/usr/bin/env PyPy3 from collections import Counter, defaultdict, deque import itertools import re import math from functools import reduce import operator import bisect from heapq import * import functools mod=998244353 import sys input=sys.stdin.readline def is_ok1(x): return (p - (q * y)) * x > pl * q def is_ok2(x): return (p - (q * y)) * x < pl * q p,q=map(int,input().split()) y = p // q pl = p - q * y - 1 pr = pl + 1 ok = q - 1 ng = 1 while ok - ng > 1: mid = (ng + ok) // 2 if is_ok1(mid): ok = mid else: ng = mid ql = ok pl += ql * y qr = q - 1 pr += qr * y g1 = math.gcd(pl,ql) pl //= g1 ql //= g1 g2 = math.gcd(pr,qr) pr //= g2 qr //= g2 print(pl + ql + pr + qr)