Solution to SICP Exercise 1.11

Structure and Interpretation of Computer Programs

Solution to Exercise 1.11:

A recursive process:

(define (fr n)
(cond ((< n 3) n)
(else (+ (fr (- n 1))
(* 2 (fr (- n 2)))
(* 3 (fr (- n 3)))))))

An iterative one:

(define (fi n)
(define (f-iter i f-i-1 f-i-2 f-i-3)
(if (> i n)
f-i-1
(f-iter (+ i 1)
(+ f-i-1 (* 2 f-i-2) (* 3 f-i-3))
f-i-1
f-i-2)))
(if (< n 3)
n
(f-iter 3 2 1 0)))

Advertisements