mirror of
https://github.com/duke-git/lancet.git
synced 2026-11-16 05:12:11 +08:00
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
This commit is contained in:
1 parent
5839ab33a9
commit
4c9c628a31
2 files changed
+44
-4
No files matched your search
+13
-4
@@ -452,9 +452,18 @@ func Combination(n, k uint) uint {
|
|||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
|
|
||||||
nFactorial := Factorial(n)
|
// C(n, k) == C(n, n-k), so the loop below runs min(k, n-k) times.
|
||||||
kFactorial := Factorial(k)
|
if k > n-k {
|
||||||
nMinusKFactorial := Factorial(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
|
||||||
}
|
}
|
||||||
@@ -2,6 +2,7 @@ package mathutil
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"math"
|
"math"
|
||||||
|
"math/bits"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/duke-git/lancet/v2/internal"
|
"github.com/duke-git/lancet/v2/internal"
|
||||||
@@ -577,9 +578,39 @@ func TestCombination(t *testing.T) {
|
|||||||
{0, 0, 1},
|
{0, 0, 1},
|
||||||
{3, 2, 3},
|
{3, 2, 3},
|
||||||
{4, 2, 6},
|
{4, 2, 6},
|
||||||
|
{5, 6, 0},
|
||||||
|
{5, 5, 1},
|
||||||
|
{5, 0, 1},
|
||||||
|
{21, 10, 352716},
|
||||||
|
{34, 17, 2333606220},
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, tt := range tests {
|
for _, tt := range tests {
|
||||||
assert.Equal(tt.expected, Combination(tt.n, tt.k))
|
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)))
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user