sicp第一章的練習題1.11
體會遞歸與迭代
將表達式f(x) 當x>=3時 f(x) = f(x-1) + 2f(x-2) + 3f(x-3), 當x<3,f(x)=x 用遞歸和迭代表示
遞歸式
(define (compute n) (cond ((< n 0) 0) ((< n 3) n) (else (+ (compute (- n 1)) (* 2 (compute (- n 2))) (* 3 (compute (- n 3))) ) ) ) )
迭代式
(define (compute2 n) (compute-iter 2 1 0 n)) (define (compute-iter a b c count) (if (= count 0) c (compute-iter (+ a (* 2 b) (* 3 c)) a b (- count 1) ) ) )