def gcd(a, b) while true do r = a % b if r == 0 return b end a = b b = r end end m, n = gets.split.map(&:to_i) while true do g = gcd(m, n) break if g == 1 m /= g n /= g end count = 0 while n != 1 do if m < n m, n = n, m count += 1 else count += m / n m = m % n end end puts count + m - 1