diff --git a/Sources/RationalModule/Rational.swift b/Sources/RationalModule/Rational.swift index 2479ef2..4bc2ba9 100644 --- a/Sources/RationalModule/Rational.swift +++ b/Sources/RationalModule/Rational.swift @@ -166,7 +166,7 @@ extension Rational { var d = denominator while true { - let a = n / d + let a = floorDivision(n, d) let q2 = q0 + a * q1 guard q2 <= max else { break } @@ -174,7 +174,7 @@ extension Rational { (n, d) = (d, n - a * d) } - let k = (max - q0) / q1 + let k = floorDivision((max - q0), q1) return if 2 * d * (q0 + k * q1) <= denominator { Self(numerator: p1, denominator: q1) } else { @@ -183,6 +183,17 @@ extension Rational { } } +/// Equivalent to Python's `//` operator. +@usableFromInline +internal func floorDivision(_ a: T, _ b: T) -> T { + let quotient = a / b + return if a >= 0 { + quotient + } else { + quotient - 1 + } +} + // MARK: - Rounding extension Rational { /// The greatest integer less than or equal to this value.