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
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
Reference in new issue
Block a user