網頁

2018年3月26日 星期一

LISP Programming 1062_ex3

http://erdos.csie.ncnu.edu.tw/~klim/scheme/lisp-1062.html

exercise 3: linear recursive and linear iterative
Refer to exercise 1.11 but the formula is changed to
  f(n) = n if n < 3
  f(n) = 2*f(n-1) + f(n-2) + f(n-3) if n ≥ 3 and n is even
  f(n) = 2*f(n-1) - f(n-2) + f(n-3) if n ≥ 3 and n is odd
Note that you have to write two procedures. One is written
in recursive way and another in linear iterative way.

解答:
;f by means of a recursive process
(define (f-res n)
    (if (< n 3)
        n  ; n<3 , f(n)=n
        (if (odd? n)
            (+ (- (* 2 (f-res (- n 1))) 
               (f-res (- n 2))) 
            (f-res (- n 3))) ; n is odd
            
            (+ (+ (* 2 (f-res (- n 1))) 
               (f-res (- n 2))) 
            (f-res (- n 3)))))) ; n is even
(define (f n)
    (f-res n))

執行結果:
 
 

沒有留言:

張貼留言