Skip to content

Instantly share code, notes, and snippets.

@shigemk2
Created July 13, 2015 15:27
Show Gist options
  • Select an option

  • Save shigemk2/83fafcff3e329daf151f to your computer and use it in GitHub Desktop.

Select an option

Save shigemk2/83fafcff3e329daf151f to your computer and use it in GitHub Desktop.
class Rational(n: Int = 1, d: Int = 1) {
private def gcd(x: Int, y: Int): Int = {
if (x == 0) y
else if (x < 0) gcd(-x, y)
else if (y < 0) -gcd(x, -y)
else gcd(y % x, x)
}
private val g = gcd(n, d)
val numer: Int = n/g
val denom: Int = d/g
def +(that: Rational) =
new Rational(numer * that.denom + that.numer * denom,
denom * that.denom)
def -(that: Rational) =
new Rational(numer * that.denom - that.numer * denom,
denom * that.denom)
def *(that: Rational) =
new Rational(numer * that.numer, denom * that.denom)
def /(that: Rational) =
new Rational(numer * that.denom, denom * that.numer)
override def toString(): String = s"${n} % ${d}"
}
val a = new Rational(1, 5)
val b = new Rational(3, 15)
val c = new Rational(3, 3)
val d = new Rational(1)
println(a)
println(b)
println(c)
println(d)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment