diff --git a/base/intfuncs.jl b/base/intfuncs.jl index a37b527ea6a1e..9f56ded57f3d3 100644 --- a/base/intfuncs.jl +++ b/base/intfuncs.jl @@ -40,7 +40,9 @@ function gcd{T<:Integer}(a::T, b::T) end abs(a) end -lcm{T<:Integer}(a::T, b::T) = abs(a * div(b, gcd(b,a))) + +# explicit a==0 test is to handle case of lcm(0,0) correctly +lcm{T<:Integer}(a::T, b::T) = a == 0 ? a : abs(a * div(b, gcd(b,a))) gcd(a::Integer) = a lcm(a::Integer) = a diff --git a/doc/helpdb.jl b/doc/helpdb.jl index 73569b7c2f589..4fbe882a20a17 100644 --- a/doc/helpdb.jl +++ b/doc/helpdb.jl @@ -3885,13 +3885,13 @@ popdisplay(d::Display) ("Mathematical Functions","Base","gcd","gcd(x, y) - Greatest common (positive) divisor + Greatest common (positive) divisor (or zero if x and y are both zero). "), ("Mathematical Functions","Base","lcm","lcm(x, y) - Least common (positive) multiple + Least common (non-negative) multiple. "), diff --git a/doc/stdlib/base.rst b/doc/stdlib/base.rst index dca8d2f5f55db..6dd17e9937580 100644 --- a/doc/stdlib/base.rst +++ b/doc/stdlib/base.rst @@ -2632,11 +2632,11 @@ Mathematical Functions .. function:: gcd(x,y) - Greatest common (positive) divisor. + Greatest common (positive) divisor (or zero if x and y are both zero). .. function:: lcm(x,y) - Least common (positive) multiple. + Least common (non-negative) multiple. .. function:: gcdx(x,y) diff --git a/test/numbers.jl b/test/numbers.jl index c257017e9c23f..251df33b4ff62 100644 --- a/test/numbers.jl +++ b/test/numbers.jl @@ -1511,3 +1511,16 @@ end # overflow in rational comparison @test 3//2 < typemax(Int) @test 3//2 <= typemax(Int) + +# check gcd and related functions against GMP +for i = -20:20, j = -20:20 + local d = gcd(i,j) + @test d >= 0 + @test lcm(i,j) >= 0 + local ib = big(i) + local jb = big(j) + @test d == gcd(ib,jb) + @test lcm(i,j) == lcm(ib,jb) + @test gcdx(i,j) == gcdx(ib,jb) + @test d != 1 || invmod(i,j) == invmod(ib,jb) +end