Skip to content

Commit 0b16e8f

Browse files
authored
faster +(::BigInt...) for more than 5 arguments (#41012)
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.
1 parent 046f11e commit 0b16e8f

File tree

2 files changed

+8
-1
lines changed

2 files changed

+8
-1
lines changed

base/gmp.jl

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -632,7 +632,9 @@ function gcdx(a::BigInt, b::BigInt)
632632
g, s, t
633633
end
634634

635-
sum(arr::AbstractArray{BigInt}) = foldl(MPZ.add!, arr; init=BigInt(0))
635+
+(x::BigInt, y::BigInt, rest::BigInt...) = sum(tuple(x, y, rest...))
636+
sum(arr::Union{AbstractArray{BigInt}, Tuple{BigInt, Vararg{BigInt}}}) =
637+
foldl(MPZ.add!, arr; init=BigInt(0))
636638
# Note: a similar implementation for `prod` won't be efficient:
637639
# 1) the time complexity of the allocations is negligible compared to the multiplications
638640
# 2) assuming arr contains similarly sized BigInts, the multiplications are much more

test/gmp.jl

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -236,10 +236,15 @@ end
236236
g = parse(BigInt,"-1")
237237

238238
@test +(a, b) == parse(BigInt,"327547")
239+
@test 327547 == sum((a, b)) isa BigInt
239240
@test +(a, b, c) == parse(BigInt,"3426495623485904783805894")
241+
@test 3426495623485904783805894 == sum((a, b, c)) isa BigInt
240242
@test +(a, b, c, d) == parse(BigInt,"3426495623485903384821764")
243+
@test 3426495623485903384821764 == sum((a, b, c, d)) isa BigInt
241244
@test +(a, b, c, d, f) == parse(BigInt,"2413804710837418037418307081437318690130968843290370569228")
245+
@test 2413804710837418037418307081437318690130968843290370569228 == sum((a, b, c, d, f)) isa BigInt
242246
@test +(a, b, c, d, f, g) == parse(BigInt,"2413804710837418037418307081437318690130968843290370569227")
247+
@test 2413804710837418037418307081437318690130968843290370569227 == sum((a, b, c, d, f, g)) isa BigInt
243248

244249
@test *(a, b) == parse(BigInt,"3911455620")
245250
@test *(a, b, c) == parse(BigInt,"13402585563389346256121263521460140")

0 commit comments

Comments
 (0)