Skip to content

Commit b58dcc5

Browse files
authored
Fix and test lcm([1//2, 1//2]) == 1//1 (#56423)
1 parent 38b41b5 commit b58dcc5

File tree

2 files changed

+17
-1
lines changed

2 files changed

+17
-1
lines changed

base/intfuncs.jl

+10-1
Original file line numberDiff line numberDiff line change
@@ -150,7 +150,16 @@ gcd(a::T, b::T) where T<:Real = throw(MethodError(gcd, (a,b)))
150150
lcm(a::T, b::T) where T<:Real = throw(MethodError(lcm, (a,b)))
151151

152152
gcd(abc::AbstractArray{<:Real}) = reduce(gcd, abc; init=zero(eltype(abc)))
153-
lcm(abc::AbstractArray{<:Real}) = reduce(lcm, abc; init=one(eltype(abc)))
153+
function lcm(abc::AbstractArray{<:Real})
154+
# Using reduce with init=one(eltype(abc)) is buggy for Rationals.
155+
l = length(abc)
156+
if l == 0
157+
eltype(abc) <: Integer && return one(eltype(abc))
158+
throw(ArgumentError("lcm has no identity for $(eltype(abc))"))
159+
end
160+
l == 1 && return abs(only(abc))
161+
return reduce(lcm, abc)
162+
end
154163

155164
function gcd(abc::AbstractArray{<:Integer})
156165
a = zero(eltype(abc))

test/intfuncs.jl

+7
Original file line numberDiff line numberDiff line change
@@ -191,6 +191,13 @@ end
191191

192192
@test lcm(T[2, 4, 6]) T(12)
193193
end
194+
195+
# Issue #55379
196+
@test lcm([1//2; 1//2]) === lcm([1//2, 1//2]) === lcm(1//2, 1//2) === 1//2
197+
@test gcd(Int[]) === 0
198+
@test lcm(Int[]) === 1
199+
@test gcd(Rational{Int}[]) === 0//1
200+
@test_throws ArgumentError("lcm has no identity for Rational{$Int}") lcm(Rational{Int}[])
194201
end
195202

196203
(a::Tuple{T, T, T}, b::Tuple{T, T, T}) where T <: Union{Int8, UInt8, Int16, UInt16, Int32, UInt32, Int64, UInt64, Int128, UInt128} = a === b

0 commit comments

Comments
 (0)