A function
f
is defined by the rule thatf(n) = n
ifn < 3
andf(n) = f(n - 1) + 2f(n - 2) + 3f(n - 3)
ifn > 3
. Write a procedure that computesf
by means of a recursive process. Write a procedure that computesf
by means of an iterative process.
Implementing it recursively is simple enough. But I couldn t figure out how to do it iteratively. I tried comparing with the Fibonacci example given, but I didn t know how to use it as an analogy. So I gave up (shame on me) and Googled for an explanation, and I found this:
(define (f n)
(if (< n 3)
n
(f-iter 2 1 0 n)))
(define (f-iter a b c count)
(if (< count 3)
a
(f-iter (+ a (* 2 b) (* 3 c))
a
b
(- count 1))))
After reading it, I understand the code and how it works. But what I don t understand is the process needed to get from the recursive definition of the function to this. I don t get how the code could have formed in someone s head.
Could you explain the thought process needed to arrive at the solution?