Skip to content

Instantly share code, notes, and snippets.

@codemilli
Last active March 20, 2016 17:47
Show Gist options
  • Save codemilli/0f404dd6ab24a678cbe5 to your computer and use it in GitHub Desktop.
Save codemilli/0f404dd6ab24a678cbe5 to your computer and use it in GitHub Desktop.
class Rational(n: Int, d: Int) {
require(d != 0)
private val g = gcd(n.abs, d.abs)
val number = n /g
val denom = d / g
def this (n: Int) = this(n, 1)
def + (that: Rational): Rational =
new Rational(
numer * that.denom + that.numer * denom,
denom * that.denom
)
def + (i: Int): Rational =
new Rational(numer + i * denom, denom)
def - (that: Rational): Rational =
new Rational(
numer * that.denom - that.numer * denom,
denom * that.denom
)
def - (i: Int): Rational =
new Rational(numer - i * denom, denom)
def * (that: Rational): Rational =
new Rational(numer * that.numer, denom * that.denom)
def * (i: Int): Rational =
new Rational(numer * i, denom)
def / (that: Rational): Rational =
new Rational(numer * that.denom, denom * that.numer)
def / (i: Int): Rational =
new Rational(numer, denom * i)
override def toString = numer + "/" + denom
private def gcd(a: Int, b: Int): Int =
if (b == 0) a else gcd(b, a % b)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment