diff --git a/base/intfuncs.jl b/base/intfuncs.jl index bc6782652c221..473fd114bc234 100644 --- a/base/intfuncs.jl +++ b/base/intfuncs.jl @@ -42,7 +42,7 @@ function gcd{T<:Integer}(a::T, b::T) g = abs(a) neg ? -g : g end -lcm{T<:Integer}(a::T, b::T) = div(a*b, gcd(b,a)) +lcm{T<:Integer}(a::T, b::T) = a * div(b, gcd(b,a)) gcd(a::Integer) = a lcm(a::Integer) = a diff --git a/base/rational.jl b/base/rational.jl index a3a7e338b6dab..b415c243523c2 100644 --- a/base/rational.jl +++ b/base/rational.jl @@ -123,8 +123,14 @@ hash(x::Rational) = isinteger(x) ? hash(x.num) : bitmix(hash(x.num), hash(x.den)) -(x::Rational) = (-x.num) // x.den -+(x::Rational, y::Rational) = (x.num*y.den + x.den*y.num) // (x.den*y.den) --(x::Rational, y::Rational) = (x.num*y.den - x.den*y.num) // (x.den*y.den) +for op in (:+, :-, :rem, :mod) + @eval begin + function ($op)(x::Rational, y::Rational) + g = gcd(x.den, y.den) + Rational(($op)(x.num * div(y.den, g), y.num * div(x.den, g)), x.den * div(y.den, g)) + end + end +end *(x::Rational, y::Rational) = (x.num*y.num) // (x.den*y.den) /(x::Rational, y::Rational) = (x.num*y.den) // (x.den*y.num) /(x::Rational, z::Complex ) = inv(z/x) @@ -149,12 +155,6 @@ hash(x::Rational) = isinteger(x) ? hash(x.num) : <=(x::Rational, y::Real ) = x.num <= x.den*y <=(x::Real , y::Rational) = x*y.den <= y.num -rem(x::Rational, y::Rational) = Rational(rem(x.num*y.den, x.den*y.num), - x.den*y.den) - -mod(x::Rational, y::Rational) = Rational(mod(x.num*y.den, x.den*y.num), - x.den*y.den) - div(x::Rational, y::Rational) = div(x.num*y.den, x.den*y.num) div(x::Rational, y::Real ) = div(x.num, x.den*y) div(x::Real , y::Rational) = div(x*y.den, y.num)