Last active
June 12, 2017 15:40
-
-
Save megri/4b07239d69dd2b66ccac9fbb601f16ee to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object Rational { | |
implicit def rationalInt(n: Int): Rational = | |
Rational(n, 1) | |
def gcd(a: Int, b: Int): Int = | |
if (b == 0) a else gcd(b, a % b) | |
} | |
case class Rational(p: Int, q: Int) { | |
require(q != 0, "Denominator 'q' cannot be 0") | |
def + (that: Rational) = | |
Rational( | |
this.p * that.q + that.p * this.q, | |
this.q * that.q | |
) | |
def - (that: Rational) = | |
Rational( | |
this.p * that.q - that.p * this.q, | |
this.q * that.q | |
) | |
def * (that: Rational) = | |
Rational( | |
this.p * that.p, | |
this.q * that.q | |
) | |
def / (that: Rational) = | |
Rational( | |
this.p * that.q, | |
this.q * that.p | |
) | |
def normalized: Rational = { | |
val gcd = Rational.gcd(p, q) | |
val lcm = p * q / gcd | |
Rational(p / gcd, q / gcd) | |
} | |
} | |
val r1 = Rational(1,5) + Rational(6,4) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment