Skip to content
Snippets Groups Projects
Commit e6d5005b authored by Nikodemus Siivola's avatar Nikodemus Siivola
Browse files

optimizations to BINOMIAL-COEFFICIENT and COUNT-PERMUATIONS

 Patch by Gustavo on alexandria-devel.

 Also add tests.
parent 4ed03a2e
No related branches found
No related tags found
No related merge requests found
...@@ -210,6 +210,10 @@ greater then K." ...@@ -210,6 +210,10 @@ greater then K."
(if (or (zerop k) (= n k)) (if (or (zerop k) (= n k))
1 1
(let ((n-k (- n k))) (let ((n-k (- n k)))
;; Swaps K and N-K if K < N-K because the algorithm
;; below is faster for bigger K and smaller N-K
(when (< k n-k)
(rotatef k n-k))
(if (= 1 n-k) (if (= 1 n-k)
n n
;; General case, avoid computing the 1x...xK twice: ;; General case, avoid computing the 1x...xK twice:
...@@ -231,8 +235,8 @@ greater then K." ...@@ -231,8 +235,8 @@ greater then K."
(defun count-permutations (n &optional (k n)) (defun count-permutations (n &optional (k n))
"Number of K element permutations for a sequence of N objects. "Number of K element permutations for a sequence of N objects.
R defaults to N" K defaults to N"
;; FIXME: Use %multiply-range and take care of 1 and 2, plus (check-type n (integer 0))
;; check types. (check-type k (integer 0))
(/ (factorial n) (assert (>= n k))
(factorial (- n k)))) (%multiply-range (1+ (- n k)) n))
...@@ -1712,3 +1712,21 @@ ...@@ -1712,3 +1712,21 @@
(1 2 3) (1 2 3)
nil nil
nil) nil)
(deftest count-permutations.1
(values (count-permutations 31 7)
(count-permutations 1 1)
(count-permutations 2 1)
(count-permutations 2 2)
(count-permutations 3 2)
(count-permutations 3 1))
13253058000
1
2
2
6
3)
(deftest binomial-coefficient.1
(alexandria:binomial-coefficient 1239 139)
28794902202288970200771694600561826718847179309929858835480006683522184441358211423695124921058123706380656375919763349913245306834194782172712255592710204598527867804110129489943080460154)
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment