Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cover binomial cases for large K (BigInt) #48073

Merged
merged 16 commits into from
Feb 28, 2023
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion base/gmp.jl
Original file line number Diff line number Diff line change
Expand Up @@ -682,8 +682,16 @@ end

factorial(x::BigInt) = isneg(x) ? BigInt(0) : MPZ.fac_ui(x)

function binomial(n::BigInt, k::Integer)
k < 0 && return BigInt(0)
k <= typemax(UInt) && return binomial(n, UInt(k))
n < 0 && return (isodd(k) ? -one(n) : one(n)) * binomial(k - n - 1, k)
originalsouth marked this conversation as resolved.
Show resolved Hide resolved
κ = n - k
κ < 0 && return BigInt(0)
κ <= typemax(UInt) && return binomial(n, UInt(κ))
throw(OverflowError("Computation will exceed memory"))
originalsouth marked this conversation as resolved.
Show resolved Hide resolved
originalsouth marked this conversation as resolved.
Show resolved Hide resolved
end
binomial(n::BigInt, k::UInt) = MPZ.bin_ui(n, k)
binomial(n::BigInt, k::Integer) = k < 0 ? BigInt(0) : binomial(n, UInt(k))

==(x::BigInt, y::BigInt) = cmp(x,y) == 0
==(x::BigInt, i::Integer) = cmp(x,i) == 0
Expand Down
10 changes: 10 additions & 0 deletions test/combinatorics.jl
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,16 @@ using Random: randcycle
@test binomial(Int64(67), Int64(29)) == binomial(BigInt(67), BigInt(29)) == 7886597962249166160
@test binomial(Int128(131), Int128(62)) == binomial(BigInt(131), BigInt(62)) == 157311720980559117816198361912717812000
@test_throws OverflowError binomial(Int64(67), Int64(30))

#Issue 48072
∐ = parse(BigInt, "1" * "0"^13 * "666" * "0"^13 * "1")
@test binomial(∐, ∐ - 1) == ∐
@test binomial(∐, ∐ - 2) == 500000000000066600000000002218280000000000033300000000000000
@test binomial(∐, ∐ - 3) == binomial(∐, 3)
@test binomial(-big(2), ∐ - 3) == 1000000000000066599999999999999
@test_throws OverflowError binomial(big(2)^65, big(2)^64)
@test_throws OverflowError binomial(-big(2)^65, big(2)^64)
@test binomial(∐, 2 * ∐) == BigInt(0)
end

@testset "permutations" begin
Expand Down