Created
July 13, 2015 15:27
-
-
Save shigemk2/83fafcff3e329daf151f to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| 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