Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Rational(x: Int, y: Int) {
- require(y != 0, "Denominator must be non-zero")
- private val g = gcd(x, y)
- def numer = x / g
- def denom = y / g
- def + (that: Rational) =
- new Rational(numer * that.denom + that.numer * denom, denom * that.denom)
- def - (that: Rational) = this + (-that)
- def * (that: Rational) = new Rational(numer * that.numer, denom * that.denom)
- def / (that: Rational) = this * (that.inv)
- def inv() = new Rational(denom, numer)
- def unary_- = new Rational(-numer, denom)
- def toDouble() = numer.toDouble / denom.toDouble
- override def toString() =
- (if (numer < 0 || denom < 0) "-" else "") + abs(numer) + "/" + abs(denom)
- private def abs(n: Int) = if (n < 0) -n else n
- private def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement