Skip to content

Commit

Permalink
faster +(::BigInt...) for more than 5 arguments (JuliaLang#41012)
Browse files Browse the repository at this point in the history
Special versions already existed upto 5 arguments. For more than 5, let's
use sum, which is optimized for an arbitrary number of arguments, and which
we also extend to tuples here for the occasion.
  • Loading branch information
rfourquet authored and johanmon committed Jul 5, 2021
1 parent 0097e69 commit 61eda0d
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 1 deletion.
4 changes: 3 additions & 1 deletion base/gmp.jl
Original file line number Diff line number Diff line change
Expand Up @@ -632,7 +632,9 @@ function gcdx(a::BigInt, b::BigInt)
g, s, t
end

sum(arr::AbstractArray{BigInt}) = foldl(MPZ.add!, arr; init=BigInt(0))
+(x::BigInt, y::BigInt, rest::BigInt...) = sum(tuple(x, y, rest...))
sum(arr::Union{AbstractArray{BigInt}, Tuple{BigInt, Vararg{BigInt}}}) =
foldl(MPZ.add!, arr; init=BigInt(0))
# Note: a similar implementation for `prod` won't be efficient:
# 1) the time complexity of the allocations is negligible compared to the multiplications
# 2) assuming arr contains similarly sized BigInts, the multiplications are much more
Expand Down
5 changes: 5 additions & 0 deletions test/gmp.jl
Original file line number Diff line number Diff line change
Expand Up @@ -236,10 +236,15 @@ end
g = parse(BigInt,"-1")

@test +(a, b) == parse(BigInt,"327547")
@test 327547 == sum((a, b)) isa BigInt
@test +(a, b, c) == parse(BigInt,"3426495623485904783805894")
@test 3426495623485904783805894 == sum((a, b, c)) isa BigInt
@test +(a, b, c, d) == parse(BigInt,"3426495623485903384821764")
@test 3426495623485903384821764 == sum((a, b, c, d)) isa BigInt
@test +(a, b, c, d, f) == parse(BigInt,"2413804710837418037418307081437318690130968843290370569228")
@test 2413804710837418037418307081437318690130968843290370569228 == sum((a, b, c, d, f)) isa BigInt
@test +(a, b, c, d, f, g) == parse(BigInt,"2413804710837418037418307081437318690130968843290370569227")
@test 2413804710837418037418307081437318690130968843290370569227 == sum((a, b, c, d, f, g)) isa BigInt

@test *(a, b) == parse(BigInt,"3911455620")
@test *(a, b, c) == parse(BigInt,"13402585563389346256121263521460140")
Expand Down

0 comments on commit 61eda0d

Please sign in to comment.