Skip to content

Instantly share code, notes, and snippets.

@cstoku
Last active May 10, 2016 06:12
Show Gist options
  • Select an option

  • Save cstoku/5f96e40e23c40a8183de2b68db3f6df1 to your computer and use it in GitHub Desktop.

Select an option

Save cstoku/5f96e40e23c40a8183de2b68db3f6df1 to your computer and use it in GitHub Desktop.
import scala.language.implicitConversions
class Rational(n : Int, d: Int) {
require(d != 0)
private val g = gcd(n.abs, d.abs)
val numer: Int = n / g
val denom: Int = d / g
def this(n: Int) = this(n, 1)
override def toString = n + "/" + d
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)
private def gcd(a: Int, b: Int): Int =
if (b == 0) a else gcd(b, a % b)
}
object Rational {
implicit def intToRational(x: Int): Rational = new Rational(x)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment