solutions/Structure and Interpretatio.../sicp-ex-1.11.rkt

28 lines
481 B
Racket
Raw Permalink Normal View History

2024-04-16 19:13:00 -04:00
; f(n) = n, when n < 3
; f(n) = f(n - 1) + f(n - 2) + f(n - 3), when n >= 3
(define fn 15)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; recursive
(define (f-rec n)
(if (< n 3)
n
(+ (+ (f-rec (- n 1))
(f-rec (- n 2)))
(f-rec (- n 3)))))
(f-rec fn)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; iterative
(define (f-iter n)
(f-iter-step 2 1 0 n))
(define (f-iter-step a b c count)
(if (< count 3)
a
(f-iter-step (+ a b c) a b (- count 1))))
(f-iter fn)