aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorWeixie Cui <cuiweixie@gmail.com>2026-04-06 10:36:44 +0000
committerGopher Robot <gobot@golang.org>2026-04-07 14:58:27 -0700
commite3b3216242691ab0e02164458bda98346ce36adf (patch)
treeaa95dd0273ddac3968928443fe3301e075a1050e
parent6f662188c2e2640712af74a01f589ee31ba0282f (diff)
downloadgo-e3b3216242691ab0e02164458bda98346ce36adf.tar.xz
math/big: Binomial should return 0 if k < 0
Fixes #78541 Change-Id: I73ba10b6d34f9f189b5bdd356d6325d5a4a6985f GitHub-Last-Rev: 0594d99f55c51f2f164d17a61c4eb1b2bbb8462e GitHub-Pull-Request: golang/go#78542 Reviewed-on: https://go-review.googlesource.com/c/go/+/763000 Auto-Submit: Robert Griesemer <gri@google.com> Reviewed-by: Robert Griesemer <gri@google.com> LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com> Reviewed-by: Neal Patel <nealpatel@google.com>
-rw-r--r--src/math/big/int.go2
-rw-r--r--src/math/big/int_test.go1
2 files changed, 2 insertions, 1 deletions
diff --git a/src/math/big/int.go b/src/math/big/int.go
index 8eb0db6c58..3c6f0d4028 100644
--- a/src/math/big/int.go
+++ b/src/math/big/int.go
@@ -227,7 +227,7 @@ func (z *Int) MulRange(a, b int64) *Int {
// Binomial sets z to the binomial coefficient C(n, k) and returns z.
func (z *Int) Binomial(n, k int64) *Int {
- if k > n {
+ if k > n || k < 0 {
return z.SetInt64(0)
}
// reduce the number of multiplications by reducing k
diff --git a/src/math/big/int_test.go b/src/math/big/int_test.go
index eb5c177be0..f6865d1ed9 100644
--- a/src/math/big/int_test.go
+++ b/src/math/big/int_test.go
@@ -255,6 +255,7 @@ func TestBinomial(t *testing.T) {
{100, 90, "17310309456440"},
{1000, 10, "263409560461970212832400"},
{1000, 990, "263409560461970212832400"},
+ {5, -1, "0"},
} {
if got := z.Binomial(test.n, test.k).String(); got != test.want {
t.Errorf("Binomial(%d, %d) = %s; want %s", test.n, test.k, got, test.want)