Advertisement
timothy235

sicp-1-2-2-tree-recursion

Feb 15th, 2016
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Racket 1.98 KB | None | 0 0
  1. #lang racket
  2.  
  3. ;; 1.11
  4.  
  5. (define (recursive-f n)
  6.   (cond [(< n 3) n]
  7.         [else (+ (recursive-f (- n 1))
  8.                  (* 2 (recursive-f (- n 2)))
  9.                  (* 3 (recursive-f (- n 3))))]))
  10.  
  11. (recursive-f 1)
  12. ;; 1
  13. (recursive-f 2)
  14. ;; 2
  15. (recursive-f 3)
  16. ;; 4
  17. (recursive-f 4)
  18. ;; 11
  19. (recursive-f 5)
  20. ;; 25
  21. (recursive-f 6)
  22. ;; 59
  23.  
  24. (define (iterative-f n)
  25.   (define (f-iter a b c cnt)
  26.     (cond [(zero? cnt) a]
  27.           [else (f-iter (+ a (* 2 b) (* 3 c))
  28.                         a
  29.                         b
  30.                         (sub1 cnt))]))
  31.   (cond [(< n 2) n]
  32.         [else (f-iter 2 1 0 (- n 2))]))
  33.  
  34. (iterative-f 1)
  35. ;; 1
  36. (iterative-f 2)
  37. ;; 2
  38. (iterative-f 3)
  39. ;; 4
  40. (iterative-f 4)
  41. ;; 11
  42. (iterative-f 5)
  43. ;; 25
  44. (iterative-f 6)
  45. ;; 59
  46.  
  47. ;; 1.12
  48.  
  49. (define (pascal row col)
  50.   (cond [(or (= col 1) ; start of row
  51.              (= row col)) ; end of row
  52.          1]
  53.         [else (+ (pascal (sub1 row) (sub1 col)) ; sum of two elements above
  54.                  (pascal (sub1 row) col))]))
  55.  
  56. (pascal 5 1)
  57. ;; 1
  58. (pascal 5 2)
  59. ;; 4
  60. (pascal 5 3)
  61. ;; 6
  62. (pascal 5 4)
  63. ;; 4
  64. (pascal 5 5)
  65. ;; 1
  66.  
  67. ;; 1.13
  68.  
  69. ;; Note that phi ^ 2 = phi + 1 and psi ^ 2 = psi + 1 because phi and psi are roots
  70. ;; of x ^ 2 - x - 1 = 0.
  71.  
  72. ;; claim:  Fib(n) = (phi ^ n - psi ^ n) / sqrt(5)
  73.  
  74. ;; Go by induction.  The base cases n = 0 and n = 1 are true.
  75.  
  76. ;; The induction step is
  77. ;; [phi ^ (n + 1) - psi ^ (n + 1)] / sqrt(5)
  78.     ;; = [phi ^ 2 * phi ^ (n - 1) - psi ^ 2 * psi ^ (n - 1)] / sqrt(5)
  79.     ;; = [(phi + 1) * phi ^ (n - 1) - (psi + 1) * psi ^ (n - 1)] / sqrt(5)
  80.     ;; = [phi ^ n + phi ^ (n - 1) - psi ^ n - psi ^ (n - 1)] / sqrt(5)
  81.     ;; = (phi ^ n - psi ^ n) / sqrt(5) + (phi ^ (n - 1) - psi ^ (n - 1)) / sqrt(5)
  82.     ;; = Fib(n) + Fib(n - 1) by induction
  83.     ;; = Fib(n + 1)
  84.  
  85. ;; That Fib(n) is the closest integer to phi ^ n / sqrt(5) follows from the above
  86. ;; claim combined with the fact that abs(psi ^ n / sqrt(5)) < 0.5.
  87.  
  88. ;; In particular Fib(n) = O(phi ^ n) is exponential.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement