diff --git a/base/intfuncs.jl b/base/intfuncs.jl index 3082b05cdd005..e312000ac39f1 100644 --- a/base/intfuncs.jl +++ b/base/intfuncs.jl @@ -117,8 +117,9 @@ function lcm(a::T, b::T) where T<:Integer end end -gcd(a::Union{Integer,Rational}) = a -lcm(a::Union{Integer,Rational}) = a +gcd(a::Integer) = checked_abs(a) +gcd(a::Rational) = checked_abs(a.num) // a.den +lcm(a::Union{Integer,Rational}) = gcd(a) gcd(a::Unsigned, b::Signed) = gcd(promote(a, abs(b))...) gcd(a::Signed, b::Unsigned) = gcd(promote(abs(a), b)...) gcd(a::Real, b::Real) = gcd(promote(a,b)...) diff --git a/test/intfuncs.jl b/test/intfuncs.jl index 24505935a2fed..8a8f046310622 100644 --- a/test/intfuncs.jl +++ b/test/intfuncs.jl @@ -12,6 +12,7 @@ using Random @test gcd(T(0), T(15)) === T(15) @test gcd(T(15), T(0)) === T(15) if T <: Signed + @test gcd(T(-12)) === T(12) @test gcd(T(0), T(-15)) === T(15) @test gcd(T(-15), T(0)) === T(15) @test gcd(T(3), T(-15)) === T(3) @@ -78,6 +79,7 @@ using Random @test lcm(T(0), T(3)) === T(0) @test lcm(T(0), T(0)) === T(0) if T <: Signed + @test lcm(T(-12)) === T(12) @test lcm(T(0), T(-4)) === T(0) @test lcm(T(-4), T(0)) === T(0) @test lcm(T(4), T(-6)) === T(12) @@ -154,6 +156,7 @@ end @test gcd(T[3, 15]) === T(3) @test gcd(T[0, 15]) === T(15) if T <: Signed + @test gcd(T[-12]) === T(12) @test gcd(T[3,-15]) === T(3) @test gcd(T[-3,-15]) === T(3) end @@ -163,12 +166,12 @@ end @test gcd(T[2, 4, 3, 5]) === T(1) @test lcm(T[]) === T(1) - @test lcm(T[2]) === T(2) @test lcm(T[2, 3]) === T(6) @test lcm(T[4, 6]) === T(12) @test lcm(T[3, 0]) === T(0) @test lcm(T[0, 0]) === T(0) if T <: Signed + @test lcm(T[-2]) === T(2) @test lcm(T[4, -6]) === T(12) @test lcm(T[-4, -6]) === T(12) end diff --git a/test/rational.jl b/test/rational.jl index 07e312543318f..aa7d48fb52513 100644 --- a/test/rational.jl +++ b/test/rational.jl @@ -488,6 +488,8 @@ end @test gcd(b, a) === T(2)//T(105) @test lcm(a, b) === T(30)//T(7) if T <: Signed + @test gcd(-a) === a + @test lcm(-b) === b @test gcdx(a, b) === (T(2)//T(105), T(-11), T(4)) @test gcd(-a, b) === T(2)//T(105) @test gcd(a, -b) === T(2)//T(105)