// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
package rational

object Rational {
  implicit def intToRational(v: Int): Rational = new Rational(v)
  def apply(n: Int, d: Int): Rational = new Rational(n, d)
  def apply(n: Int): Rational = new Rational(n)
}

class Rational (n: Int, d: Int){
  val (nv, dv) = reduce(n, d)
  def this(n: Int) = this(n, 1)
  def +(other: Rational): Rational = new Rational(nv*other.dv + other.nv*dv, dv*other.dv)
  def -(other: Rational): Rational = new Rational(nv*other.dv - other.nv*dv, dv*other.dv)
  def *(other: Rational): Rational = new Rational(nv*other.nv, dv*other.dv)
  def /(other: Rational): Rational = new Rational(nv*other.dv, dv*other.nv)
  def +(other: Int): Rational = this + new Rational(other)
  def -(other: Int): Rational = this - new Rational(other)
  def *(other: Int): Rational = this * new Rational(other)
  def /(other: Int): Rational = this / new Rational(other)
  def reduce(n: Int, d: Int): (Int,Int) = (n/gcd(n, d), d/gcd(n, d))
  def gcd(a: Int, b: Int): Int = if(b==0) a else gcd(b, a%b)
  override def toString(): String = n + "/" + d
}
