Created
July 13, 2014 22:37
-
-
Save mohanrajendran/7f956d0ce0c9b89a9abe to your computer and use it in GitHub Desktop.
SICP Exercise 1.11
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;;; Original function | |
(define (f n) | |
(cond ((< n 3) n) | |
(else (+ (f (- n 1)) (* 2 (f (- n 2))) (* 3 (f (- n 3))))))) | |
; f | |
(f 0) | |
; 0 | |
(f 1) | |
; 1 | |
(f 2) | |
; 2 | |
(f 3) | |
; 4 | |
(f 4) | |
; 11 | |
(f 5) | |
; 25 | |
(f 10) | |
; 1892 | |
;;; Iterative version | |
(define (f-iter a b c count) | |
(cond ((= count 0) c) | |
(else (f-iter (+ a (* 2 b) (* 3 c)) a b (- count 1))))) | |
; f-iter | |
(define (f n) (f-iter 2 1 0 n)) | |
; f | |
;; Test cases | |
(f 0) | |
; 0 | |
(f 1) | |
; 1 | |
(f 2) | |
; 2 | |
(f 3) | |
; 4 | |
(f 4) | |
; 11 | |
(f 5) | |
; 25 | |
(f 10) | |
; 1892 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment