Advertisement
Guest User

Untitled

a guest
Sep 6th, 2014
253
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 0.84 KB | None | 0 0
  1.  
  2. class Rational(x: Int, y: Int) {
  3.     require(y != 0, "Denominator must be non-zero")
  4.     private val g = gcd(x, y)
  5.     def numer = x / g
  6.     def denom = y / g
  7.  
  8.     def + (that: Rational) =
  9.         new Rational(numer * that.denom + that.numer * denom, denom * that.denom)
  10.  
  11.     def - (that: Rational) = this + (-that)
  12.  
  13.     def * (that: Rational) = new Rational(numer * that.numer, denom * that.denom)
  14.  
  15.     def / (that: Rational) = this * (that.inv)
  16.  
  17.     def inv() = new Rational(denom, numer)
  18.  
  19.     def unary_- = new Rational(-numer, denom)
  20.  
  21.     def toDouble() = numer.toDouble / denom.toDouble
  22.  
  23.     override def toString() =
  24.         (if (numer < 0 || denom < 0) "-" else "") + abs(numer) + "/" + abs(denom)
  25.  
  26.     private def abs(n: Int) = if (n < 0) -n else n
  27.  
  28.     private def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)
  29. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement