Difficulty: Easy
Topic: Fibonacci seqs
Write a function which returns the first X fibonacci numbers.
;; 首先实现一个求fibonacci数的函数
;;最简单的实现,就是通过定义来实现递归函数,(如下的fibonacci-number),但是这样缺点很明显,首先这不算尾递归,代码里面有大量的重复计算。其次,jvm不支持尾调用优化,因此,即使是尾递归,当嵌套层侧过深时,也会出现stackoverflow,
;; bad implementation!!!
(defn fibonacci-number [number]
(cond
(= 1 number) 1
(= 2 number) 1
:default (+ (fibonacci-number (- number 1))
(fibonacci-number (- number 2)))))
;; also bad implementation!!!
(defn fib-num-helper [num result1 result2]
(cond
(= 1 num) result1
(= 2 num) result2
:default (fib-num-helper (dec num) result2 (+ result1 result2))))
;;test
(fib-num-helper 3 1 1)
;;not good
(defn fib-num [num]
(let [result1 1
result2 1]
((fn helper [n r1 r2]
(cond
(= 1 n) r1
(= 2 n) r2
:default (helper (dec n) r2 (+ r1 r2))))
num result1 result2)))
;;test
(fib-num 14)
(defn new-fib-num [num]
(defn new-fib-num-helper [counter
limit
result1
result2
r-seq]
(cond
(= counter limit) (seq r-seq)
:default (recur (inc counter)
limit
result2
(+ result1 result2)
(conj r-seq result2))))
(new-fib-num-helper 1
num
1
1
[1]))
;;test
(new-fib-num 4)
(new-fib-num 8)