def extended_gcd(a, b): if b == 0: return (a, 1, 0) else: g, x, y = extended_gcd(b, a % b) return (g, y, x - (a // b) * y) def modinv(a, m): g, x, y = extended_gcd(a, m) if g != 1: return None # This should not happen as per problem constraints else: return x % m # Read input P, Q = map(int, input().split()) # Compute inverse of P modulo Q inv_p = modinv(P, Q) # Calculate left fraction (a_left / b_left) b_left = inv_p a_left = (b_left * P - 1) // Q # Calculate right fraction (c_right / d_right) d_right = (-inv_p) % Q c_right = (d_right * P + 1) // Q # Sum all components total = a_left + b_left + c_right + d_right print(total)