e1.11.scm 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. ; f(n) = { n if n < 3
  2. ; f(n - 1) + 2f(n - 2) + 3f(n - 3) if n > 3
  3. ; linear recursive process implementation
  4. (define (f n)
  5. (cond ((< n 3) n)
  6. (else (+ (* 1 (f (- n 1)))
  7. (* 2 (f (- n 2)))
  8. (* 3 (f (- n 3)))))))
  9. (f 2)
  10. (f 3)
  11. (f 4)
  12. (f 5)
  13. (f 10)
  14. ; linear iterative process implementation
  15. ; the idea here is to keep a growing sum of values, accumulated within c
  16. ; with every iteration the precomputed values of c bubble to b and later to a
  17. ; i begins at n and is decremented for a total of n iterations (simple iterator)
  18. ; our base case is for our base cases 1, 2 and 3, the values are held within a, b and c respectively, and bubble timely to a to be evaluated at our iteration's base case (= i 0)
  19. ; as computation really only sets off for n >= 3, a, b and c are set as
  20. ; a = n - 3
  21. ; b = n - 2
  22. ; c = n - 1
  23. ; respectively
  24. ; a = 0; b = 1; c = 2;
  25. ; for (i = n; i >= 0; i--) {
  26. ; t_c = c; t_b = b;
  27. ; c = 3*a + 2*b + c;
  28. ; b = t_c;
  29. ; a = t_b;
  30. ; }
  31. (define (f2-iter i a b c)
  32. (cond ((= i 0) a)
  33. (else
  34. (f2-iter (- i 1)
  35. b
  36. c
  37. (+ (* 3 a)
  38. (* 2 b)
  39. c)))))
  40. (define (f2 n) (f2-iter n 0 1 2))
  41. (f2 2)
  42. (f2 3)
  43. (f2 4)
  44. (f2 5)
  45. (f2 10)