better Fibonacci function

This commit is contained in:
Pekka Laiho 2020-12-07 09:38:39 +07:00
parent 086765d286
commit 1151ebe336

View File

@ -1,16 +1,11 @@
;; Functions to calculate Fibonacci numbers ;; Functions to calculate Fibonacci numbers
;; Recursive, tail call optimized
(defn fibRec (i n a b) (if (= i n) (+ a b) (fibRec (inc i) n b (+ a b))))
(defn fib (n) (if (< n 2) n (fibRec 2 n 0 1)))
;; Return a vector of n Fibonacci numbers
(defn fibVec (n) (map fib (range n)))
;; Slow recursive version ;; Slow recursive version
(defn slowFib (n) (if (< n 2) n (+ (slowFib (- n 1)) (slowFib (- n 2))))) (defn slowFib (n) (if (< n 2) n (+ (slowFib (- n 1)) (slowFib (- n 2)))))
;; Return the sum of the last 2 numbers in a sequence
(defn sumOfLast (l) (+ (last l) (penult l)))
;; Faster version, return vector of n numbers, tail call optimized
(defn fibListRec (n l) (if (< (len l) n) (fibListRec n (push l (sumOfLast l))) l))
(defn fibList (n) (fibListRec n [0 1]))
(defn fastFib (n) (sumOfLast (fibList n)))
;; Add docstrings
(doc slowFib "Return the nth number from the Fibonacci sequence recursively.")
(doc fastFib "Return the nth number from the Fibonacci sequence iteratively.")