SICP:1.19快速的求Fib数列

#lang racket

(define (fib n) 
  (fib-iter 1 0 0 1 n)
  );fib

(define (fib-iter a b p q count)
  (cond ((= count 0) b);0
    ((even? count)
     (fib-iter a
           b
           (+ (* p p) (* q q))
           (+ (* q q) (* 2 p q))
           (/ count 2)));even?
    (else (fib-iter (+ (* b q) (* a q) (* a p) );+
            (+ (* b p) (* a q) );+
                    p
            q
            (- count 1))
     );else
   );cond  
 );fib-iter

(define (even? n) 
  (= (remainder n 2)
     0)
  );even?

(fib 1)
(fib 2)
(fib 3)
(fib 4)
(fib 5)

;T(pq):(a,b)=>(bq+aq+ap, bp+aq)
;T(pq):(bq+aq+ap, bp+aq)=>((bp+aq)q + (bq+aq+ap)q + (bq+aq+ap)p,
;                          (bp+aq)p + (bq+aq+ap)q)
;      => (2bpq+2aqq+bqq+2apq+app, bpp+2apq+bqq+aqq)
;      => (b(2pq+qq)+a(2pq+qq)+a(qq+pp), b(qq+pp)+a(2pq+qq))
;q' = 2pq+qq
;p' = qq+pp
;

 

也可以使用矩阵的快速幂乘

posted on 2015-03-23 20:50  Zachary_wiz  阅读(191)  评论(0编辑  收藏  举报

导航