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.
recursive:
(define (fn n)
(cond ((>= n 3) (+ (+ (fn (- n 1)) (* 2 (fn (- n 2)))) (* 3 (fn (- n 3)))))
((< n 3) n)
))
iterative:
(define (re n)
(if (< n 3)
n
(iter 2 1 0 n)
))
(define (iter a b c n)
(if(= n 3)
(ca a b c)
(iter (ca a b c) a b (- n 1))
)
)
(define (ca a b c)
(+ a (* 2 b) (* 3 c) )
)
posted on 2009-03-10 08:51
lzj520 阅读(204)
评论(0) 编辑 收藏 所属分类:
个人学习日记 、
sicp