Created
February 15, 2023 03:01
-
-
Save felipeska/457089e6fcf9ee1bb00ef7986abcf5e1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package rationals | |
import java.math.BigInteger | |
data class Rational(val n: BigInteger, val d: BigInteger): Comparable<Rational> { | |
init { require(d != BigInteger.ZERO ) {"Zero is not allowed in the denominator"} } | |
override fun toString(): String { | |
if (this.d == BigInteger.ONE) return "${this.n}" | |
return "$n/$d" | |
} | |
override fun compareTo(other: Rational): Int { | |
return n.times(other.d).compareTo(other.n.times(d)) | |
} | |
} | |
fun String.toRational(): Rational = if (this.contains("/")) { | |
val split = this.split("/") | |
val n = split[0].toBigInteger() | |
val d = split[1].toBigInteger() | |
// normalize | |
val g = n.gcd(d) | |
val num = n / g | |
val den = d / g | |
if(den < BigInteger.ZERO) | |
Rational(-num, den.abs()) | |
else | |
Rational(num, den) | |
} else { | |
Rational(this.toBigInteger(), BigInteger.ONE) | |
} | |
infix fun Int.divBy(d: Int): Rational = Rational(this.toBigInteger(), d.toBigInteger()).toString().toRational() | |
infix fun Long.divBy(d: Long): Rational = Rational(this.toBigInteger(), d.toBigInteger()).toString().toRational() | |
infix fun BigInteger.divBy(d: BigInteger): Rational = Rational(this, d).toString().toRational() | |
operator fun Rational.unaryMinus(): Rational = Rational(-this.n, this.d) | |
operator fun Rational.plus(other: Rational): Rational { | |
return if (this.d == other.d) { | |
val n = this.n + other.n | |
val d = this.d | |
Rational(n, d).toString().toRational() | |
} else { | |
val d = this.d * other.d | |
val na = this.n * other.d | |
val nb = other.n * this.d | |
val n = na + nb | |
Rational(n, d).toString().toRational() | |
} | |
} | |
operator fun Rational.minus(other: Rational): Rational { | |
return if (this.d == other.d) { | |
val n = this.n + other.n | |
val d = this.d | |
Rational(n, d).toString().toRational() | |
} else { | |
val d = this.d * other.d | |
val na = this.n * other.d | |
val nb = other.n * this.d | |
val n = na - nb | |
Rational(n, d).toString().toRational() | |
} | |
} | |
operator fun Rational.times(other: Rational): Rational = | |
Rational(this.n * other.n, this.d * other.d).toString().toRational() | |
operator fun Rational.div(other: Rational): Rational { | |
val n = this.n * other.d | |
val d = this.d * other.n | |
return Rational(n, d).toString().toRational() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment