From 4c9c628a3196fe51997f61b1007c25ec064e81bf Mon Sep 17 00:00:00 2001 From: Lee Sang Gyu Date: Mon, 9 Nov 2026 18:37:55 +0900 Subject: [PATCH] fix(package): [mathutil] compute Combination without factorial overflow (#414) * fix(package): [mathutil] compute Combination without factorial overflow * test(package): [mathutil] cover Combination for large n --- mathutil/mathutil.go | 17 +++++++++++++---- mathutil/mathutil_test.go | 31 +++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 4 deletions(-) diff --git a/mathutil/mathutil.go b/mathutil/mathutil.go index f246acd..23faa42 100644 --- a/mathutil/mathutil.go +++ b/mathutil/mathutil.go @@ -452,9 +452,18 @@ func Combination(n, k uint) uint { return 0 } - nFactorial := Factorial(n) - kFactorial := Factorial(k) - nMinusKFactorial := Factorial(n - k) + // C(n, k) == C(n, n-k), so the loop below runs min(k, n-k) times. + if k > n-k { + k = n - k + } - return nFactorial / (kFactorial * nMinusKFactorial) + // Build C(n-k+i, i) for i = 1..k. Each step is an exact integer, and dividing + // by the gcd first avoids the overflow of computing the factorials of n and k. + result := uint(1) + for i := uint(1); i <= k; i++ { + g := gcd(result, i) + result = result / g * ((n - k + i) / (i / g)) + } + + return result } diff --git a/mathutil/mathutil_test.go b/mathutil/mathutil_test.go index 4350608..d477c21 100644 --- a/mathutil/mathutil_test.go +++ b/mathutil/mathutil_test.go @@ -2,6 +2,7 @@ package mathutil import ( "math" + "math/bits" "testing" "github.com/duke-git/lancet/v2/internal" @@ -577,9 +578,39 @@ func TestCombination(t *testing.T) { {0, 0, 1}, {3, 2, 3}, {4, 2, 6}, + {5, 6, 0}, + {5, 5, 1}, + {5, 0, 1}, + {21, 10, 352716}, + {34, 17, 2333606220}, } for _, tt := range tests { assert.Equal(tt.expected, Combination(tt.n, tt.k)) } } + +func TestCombinationLarge(t *testing.T) { + t.Parallel() + + if bits.UintSize < 64 { + t.Skip("the expected values do not fit in a 32-bit uint") + } + + assert := internal.NewAssert(t, "TestCombinationLarge") + + tests := []struct { + n uint + k uint + expected uint64 + }{ + {40, 20, 137846528820}, + {60, 30, 118264581564861424}, + {62, 31, 465428353255261088}, + {64, 32, 1832624140942590534}, + } + + for _, tt := range tests { + assert.Equal(tt.expected, uint64(Combination(tt.n, tt.k))) + } +}