This is the recursive procedure for a function f(n) = n if n<3 and f(n) = f(n - 1) + 2f(n - 2) + 3f(n - 3) if n ≥ 3
(define (f n) (if (< n 3) n (+ (f (- n 1)) (* 2 (f (- n 2))) (* 3 (f (- n 3)))))) The problem set is to change it to an iterative recursion. I came up with this:
(define (g n) (if (< n 3) n (g-helper n))) (define (g-helper n) (if (< n 3) n (+ (basemaker 0 1 (- n 1)) (g-helper (- n 1)) (* 2 (basemaker 0 2 (- n 2)) (g-helper (- n 2))) (* 3 (basemaker 0 3 (- n 3)) (g-helper (- n 3)))))) (define (basemaker counter constant n) (cond ((= 2 n) 2) ((= 1 n) 1) ((= 0 n) 0) (else (basemaker (+ counter constant) constant (- n constant))))) Something is wrong:
> (f 3) 4 > (f 4) 11 > (f 5) 25 > (g 3) 6 > (g 4) 19 > (g 5) 45 > Spent hours on this, but I can't see what I'm doing wrong. I know the code is repetitive and clunky, but I would like to see what I have not understood about the process before I refine the syntax.
Thanks.