sicp第一章看完了回头做上面的练习题,发现很多东西根本没有弄懂。由于这本书比较难,精力时间有限,打算暑假看完前面两章,完成习题,第三章简略看下,最后两章以后再看。
书上内容都很精细,所以博客里也不会写太多书上的内容,如果感兴趣可以直接看书。博客里主要记录一些解题思路,和延伸的知识。
一、练习题
Exercise 1.11 gives us a function defined by the rules that
and asks us to write both recursive and iterative procedures for the function.
要求分别写出递归计算过程和迭代计算过程。
下面代码是scheme(lisp的一种方言)写的:
(define (f n) (cond ((< n 3) n) (else (+ (f (- n 1)) (* 2 (f (- n 2))) (* 3 (f (- n 3))))))) ;the function is f(n) = f(n-1) + 2f(n-2) + 3f(n-3) ;f(n) :a b c is n n-1 n-2 ;f(n+1): a+2b+3c a b is n+1 n n-1 (define (f-iter a b c count) (if (< count 3) a (f-iter (+ a (* 2 b) (* 3 c)) a b (- count 1)))) (define (fi n) (f-iter 2 1 0 n))
其中f函数是递归计算过程,函数fi是迭代计算过程。迭代比递归效率高很多,但是写起来费脑力。
迭代可以参考之前斐波那切数列python版本的尾递归http://my.oschina.net/hebianxizao/blog/62328,只不过,这题里多了一个变量。
还有一道题目:
Exercise 1.13 asks us to prove that Fib(n) is the closest integer to φn/√5, where