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 process:
(define (fn x)
(if (< x 3)
x
(+ (fn (- x 1))
(* 2 (fn (- x 2)))
(* 3 (fn (- x 3))))))iterative process:
(define (fn-iter f1 f2 f3 count)
(cond ((= count 0) f3)
((= count 1) f2)
((= count 2) f1)
(else (fn-iter (+ f1
(* 2 f2)
(* 3 f3))
f1
f2
(- count 1)))))
(define (fn2 n)
(if (< n 3)
n
(fn-iter 2 1 0 n)))
本文介绍了如何使用递归过程和迭代过程来实现一个特定的数学函数。该函数对于小于3的输入直接返回输入值,对于大于等于3的输入则通过递归调用自身计算前三个数值的组合。文中提供了两种计算方法的具体Scheme语言实现。
1819

被折叠的 条评论
为什么被折叠?



