diff --git a/Math.ark b/Math.ark index 2eab946..e04c466 100644 --- a/Math.ark +++ b/Math.ark @@ -766,20 +766,26 @@ # @details Evaluates to n! / (k! * (n - k)!) when k <= n and evaluates to zero when k > n. # @param _n total number of items # @param _k number of items that will be picked -# @author https://github.com/SuperFola +# @author https://github.com/SuperFola, https://github.com/kg583 (let binomialCoeff (fun (_n _k) (if (<= _k _n) - (/ (factorial _n) (* (factorial _k) (factorial (- _n _k)))) + (/ (permutations _n _k) (factorial _k)) 0))) # @brief Compute the number of ways to choose k items from n items without repetition and with order # @details Evaluates to n! / (n - k)! when k <= n and evaluates to zero when k > n. # @param _n total number of items # @param _k number of items to pick -# @author https://github.com/SuperFola -(let permutations (fun (_n _k) +# @author https://github.com/SuperFola, https://github.com/kg583 +(let permutations (fun ((mut _n) _k) (if (<= _k _n) - (/ (factorial _n) (factorial (- _n _k))) + { + (mut _res 1) + (let _lower (- _n _k)) + (while (> _n _lower) { + (set _res (* _res _n)) + (set _n (- _n 1)) }) + _res } 0))) # @brief Compare two real numbers and return true if the first one is near the second one (1e-7 precision) diff --git a/tests/math-tests.ark b/tests/math-tests.ark index a2d192a..cc4a8d9 100644 --- a/tests/math-tests.ark +++ b/tests/math-tests.ark @@ -298,7 +298,8 @@ (test:eq (math:binomialCoeff 4 1) 4) (test:eq (math:binomialCoeff 4 2) 6) (test:eq (math:binomialCoeff 4 3) 4) - (test:eq (math:binomialCoeff 4 4) 1) }) + (test:eq (math:binomialCoeff 4 4) 1) + (test:eq (math:binomialCoeff 90 13) 1643385429346680) }) (test:case "permutations" { (test:eq (math:permutations 5 3) 60)