Skip to content

Commit

Permalink
chore: cleanup simplifyFraction
Browse files Browse the repository at this point in the history
  • Loading branch information
lbressler13 committed Jan 31, 2024
1 parent c839198 commit 8317933
Showing 1 changed file with 11 additions and 17 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -13,26 +13,20 @@ import java.math.BigInteger
* @return Pair<BigInteger, BigInteger>: pair where first value represents simplified numerator, and second value represents simplified denominator
*/
internal fun simplifyFraction(numerator: BigInteger, denominator: BigInteger): Pair<BigInteger, BigInteger> {
var newNumerator = numerator
var newDenominator = denominator

// set denominator to 1 when numerator is 0
if (newNumerator.isZero()) {
newDenominator = BigInteger.ONE
}

// move negatives to numerator
if (newDenominator.isNegative()) {
newNumerator = -newNumerator
newDenominator = -newDenominator
if (numerator.isZero()) {
return Pair(BigInteger.ZERO, BigInteger.ONE)
}

// simplify using greatest common divisor
if (newNumerator != BigInteger.ZERO) {
val gcd = getGCD(newNumerator, newDenominator)
newNumerator /= gcd
newDenominator /= gcd
}
val gcd = getGCD(numerator, denominator)
val simplifiedNumerator = numerator / gcd
val simplifiedDenominator = denominator / gcd

return Pair(newNumerator, newDenominator)
// move negatives to numerator
return if (denominator.isNegative()) {
Pair(-simplifiedNumerator, -simplifiedDenominator)
} else {
Pair(simplifiedNumerator, simplifiedDenominator)
}
}

0 comments on commit 8317933

Please sign in to comment.