Skip to content

Instantly share code, notes, and snippets.

@bjarkevad
Last active December 25, 2015 14:19
Show Gist options
  • Save bjarkevad/6990250 to your computer and use it in GitHub Desktop.
Save bjarkevad/6990250 to your computer and use it in GitHub Desktop.
Rational number
class Rational(n: Int, d: Int) {
require(d != 0, "Denominator must be nonzero")
def this(n: Int) = this(n, 1)
private def gcd(a: Int, b: Int): Int =
if (b == 0) a else gcd(b, a % b)
private val g = gcd(n, d)
val numer = n / g
val denom = d / g
def +(that: Rational) =
new Rational(
numer * that.denom + that.numer * denom,
denom * that.denom)
def -(that: Rational) =
this + -that
def unary_- = new Rational(-numer, denom)
def <(that: Rational) =
numer * that.denom < that.numer * denom
def max(that: Rational) =
if (this < that) that else this
override def toString = numer + "/" + denom
def toDouble = numer.toDouble / denom.toDouble
}
val x = new Rational(1, 3)
val y = new Rational(5, 7)
val z = new Rational(3, 2)
-x
x - y - z
y + y
x < y
x.max(y)
val r = new Rational(2)
x.toDouble
x + y
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment