Skip to content

Commit

Permalink
Fix and test lcm([1//2, 1//2]) == 1//1 (#56423)
Browse files Browse the repository at this point in the history
  • Loading branch information
LilithHafner authored Jan 8, 2025
1 parent 38b41b5 commit b58dcc5
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
11 changes: 10 additions & 1 deletion base/intfuncs.jl
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,16 @@ gcd(a::T, b::T) where T<:Real = throw(MethodError(gcd, (a,b)))
lcm(a::T, b::T) where T<:Real = throw(MethodError(lcm, (a,b)))

gcd(abc::AbstractArray{<:Real}) = reduce(gcd, abc; init=zero(eltype(abc)))
lcm(abc::AbstractArray{<:Real}) = reduce(lcm, abc; init=one(eltype(abc)))
function lcm(abc::AbstractArray{<:Real})
# Using reduce with init=one(eltype(abc)) is buggy for Rationals.
l = length(abc)
if l == 0
eltype(abc) <: Integer && return one(eltype(abc))
throw(ArgumentError("lcm has no identity for $(eltype(abc))"))
end
l == 1 && return abs(only(abc))
return reduce(lcm, abc)
end

function gcd(abc::AbstractArray{<:Integer})
a = zero(eltype(abc))
Expand Down
7 changes: 7 additions & 0 deletions test/intfuncs.jl
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,13 @@ end

@test lcm(T[2, 4, 6]) T(12)
end

# Issue #55379
@test lcm([1//2; 1//2]) === lcm([1//2, 1//2]) === lcm(1//2, 1//2) === 1//2
@test gcd(Int[]) === 0
@test lcm(Int[]) === 1
@test gcd(Rational{Int}[]) === 0//1
@test_throws ArgumentError("lcm has no identity for Rational{$Int}") lcm(Rational{Int}[])
end

(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
Expand Down

0 comments on commit b58dcc5

Please sign in to comment.