From SICP
Exercise 1.11: A function \$f\$ is defined by the rule that:
\$f(n) = n\$ if \$n < 3\$, and
\$f(n) = f(n-1)+2f(n-2)+3f(n-3)\$ if \$n >= 3\$.
- Write a procedure that computes f by means of a recursive process.
- Write a procedure that computes f by means of an iterative process.
Please review my code.
I think the recursive process is obvious enough but I put it here just in case it could be improved.
(define (f n)
(if (< n 3) n
(+ (f (- n 1))
(* 2 (f (- n 2)))
(* 3 (f (- n 3))))))
Now, here's the iterative process. I followed the relationship created by the fibonacci example. The idea is:
- \$a = f(n+2)\$
- \$b = f(n+1)\$
- \$c = f(n)\$
(define (f n)
(f-iter 2 1 0 n))
(define (f-iter a b c count)
(if (= count 0)
c
(f-iter (+ a (* 2 b) (* 3 c)) a b (- count 1))))
How to make this code better and faster? Are there more efficient ways?