問題5.28 – SICP(計算機プログラムの構造と解釈)その278
2009年11月17日
問題5.28
評価器を末尾再帰的でないように ev-sequence を変更(p333)し、それぞれの版の factorial を実行する。
反復的手続きの場合
;;; EC-Eval input:
(define (factorial n)
(define (iter product counter)
(if (> counter n)
product
(iter (* counter product)
(+ counter 1))))
(iter 1 1))
(total-pushes = 3 maximum-depth = 3)
;;; EC-Eval value:
ok
;;; EC-Eval input:
(factorial 3)
(total-pushes = 144 maximum-depth = 23)
;;; EC-Eval value:
6
;;; EC-Eval input:
(factorial 4)
(total-pushes = 181 maximum-depth = 26)
;;; EC-Eval value:
24
;;; EC-Eval input:
(factorial 5)
(total-pushes = 218 maximum-depth = 29)
;;; EC-Eval value:
120
;;; EC-Eval input:
(factorial 6)
(total-pushes = 255 maximum-depth = 32)
;;; EC-Eval value:
720
;;; EC-Eval input:
(factorial 7)
(total-pushes = 292 maximum-depth = 35)
;;; EC-Eval value:
5040
;;; EC-Eval input:
(factorial 8)
(total-pushes = 329 maximum-depth = 38)
;;; EC-Eval value:
40320
反復的手続きの factorial の計算に利用するスペースが線形に増加するようになってしまう。
| n | total-pushes | maximum-depth |
|---|---|---|
| 3 | 144 | 23 |
| 4 | 181 | 26 |
| 5 | 218 | 29 |
| 6 | 255 | 32 |
| 7 | 292 | 35 |
| 8 | 329 | 38 |
再帰的手続きの場合
;;; EC-Eval input:
(define (factorial n)
(if (= n 1)
1
(* (factorial (- n 1)) n)))
(total-pushes = 3 maximum-depth = 3)
;;; EC-Eval value:
ok
;;; EC-Eval input:
(factorial 3)
(total-pushes = 86 maximum-depth = 27)
;;; EC-Eval value:
6
;;; EC-Eval input:
(factorial 4)
(total-pushes = 120 maximum-depth = 35)
;;; EC-Eval value:
24
;;; EC-Eval input:
(factorial 5)
(total-pushes = 154 maximum-depth = 43)
;;; EC-Eval value:
120
;;; EC-Eval input:
(factorial 6)
(total-pushes = 188 maximum-depth = 51)
;;; EC-Eval value:
720
;;; EC-Eval input:
(factorial 7)
(total-pushes = 222 maximum-depth = 59)
;;; EC-Eval value:
5040
;;; EC-Eval input:
(factorial 8)
(total-pushes = 256 maximum-depth = 67)
;;; EC-Eval value:
40320
| n | total-pushes | maximum-depth |
|---|---|---|
| 3 | 86 | 27 |
| 4 | 120 | 35 |
| 5 | 154 | 43 |
| 6 | 188 | 51 |
| 7 | 222 | 59 |
| 8 | 256 | 67 |
計算機プログラムの構造と解釈
posted with amazlet at 08.11.07
ジェラルド・ジェイ サスマン ジュリー サスマン ハロルド エイブルソン
ピアソンエデュケーション
売り上げランキング: 6542
ピアソンエデュケーション
売り上げランキング: 6542
