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 recursive and an iterative process for computing f(n).
I wrote the following:
(define (f_r n)
; recursive
(cond ((< n 3) n)
(else (+ (f_r (- n 1))
(* 2 (f_r (- n 2)))
(* 3 (f_r (- n 3)))))))
(define (f_i n)
;iterative
(f_i-prime 1 0 0 n))
(define (f_i-prime n n-1 n-2 count)
(cond ((= count 0) n)
((f_i-prime (+ n n-1 n-2)
(+ n n-1)
n-1
(- count 1)))))
What do you think?
EDIT 1: Since my first iterative solution was erroneous, here is a corrected version:
(define (f_i n)
;iterative
(f_i-prime 2 1 0 n))
(define (f_i-prime f_x+2 f_x+1 f_x n-x)
(cond ((= n-x 0) f_x)
((f_i-prime (+ f_x+2 (* 2 f_x+1) (* 3 f_x) )
f_x+2
f_x+1
(- n-x 1)))))