Rational Number - cphbus-android/general GitHub Wiki

data class Rational(val n: Int, val d: Int) {

    val gcd: Int by lazy {
        gcd(n, d)
        }

    private fun gcd(a: Int, b: Int) : Int =
        if (b == 0) a
        else gcd(b, a%b)

    val text: String
        get() = "${n/gcd}/${d/gcd}"


    operator fun times(other: Rational) =
            Rational(
                    this.n*other.n,
                    this.d*other.d
                    )
    operator fun div(other: Rational) =
            Rational(
                    this.n*other.d,
                    other.n*this.d
                    )
    operator fun plus(other: Rational) =
            Rational(
                    this.n*other.d + other.n*this.d,
                    this.d*other.d
                    )
    operator fun minus(other: Rational) =
            Rational(
                    this.n*other.d - other.n*this.d,
                    this.d*other.d
                    )
    operator fun times(i: Int) = Rational(i*n, d)
    }

operator fun Int.times(r: Rational) = Rational(this*r.n, r.d)

val Int.rational: Rational
    get() = Rational(this, 1)