[问题] 费氏数列快速计算的 scheme 程式

楼主: hijkxyzuw (i,j,k) ×(x,y,z)   2017-09-03 11:29:59
最近在读 sicp ,在 1-2-4 章,
有介绍一种将 n 次计算简化为 log(n) 次的作法。
他应用在费氏数列上,但他使用的费氏数列算法我看不懂……。
原文:
> *Exercise 1.19:* There is a clever algorithm for computing the
> Fibonacci numbers in a logarithmic number of steps. Recall the
> transformation of the state variables a and b in the 'fib-iter'
> process of section *note 1-2-2::: a <- a + b and b <- a. Call this
> transformation T, and observe that applying T over and over again n
> times, starting with 1 and 0, produces the pair _Fib_(n + 1) and
> _Fib_(n). In other words, the Fibonacci numbers are produced by
> applying T^n, the nth power of the transformation T, starting with
> the pair (1,0). Now consider T to be the special case of p = 0 and
> q = 1 in a family of transformations T_(pq), where T_(pq)
> transforms the pair (a,b) according to a <- bq + aq + ap and b <-
> bp + aq. Show that if we apply such a transformation T_(pq) twice,
> the effect is the same as using a single transformation T_(p'q') of
> the same form, and compute p' and q' in terms of p and q. This
> gives us an explicit way to square these transformations, and thus
> we can compute T^n using successive squaring, as in the 'fast-expt'
> procedure. Put this all together to complete the following
> procedure, which runs in a logarithmic number of steps:(5)
别人的 scheme 程式码:
(define (fib n)
(define (even? n)
(= (remainder n 2) 0))
(define (fib-iter a b p q count)
(display (list a b p q count)) (newline)
(cond ((= count 0) b)
((even? count)
(fib-iter a
b
(+ (square p) (square q))
(+ (* 2 p q) (square q))
(/ count 2)))
(else
(fib-iter (+ (* b q) (* a q) (* a p))
(+ (* b p) (* a q))
p
q
(- count 1)))))
(fib-iter 1 0 0 1 n))
翻译成 javascript :
(应该算比较多人懂的程式语言)
function fib(n) {
return iter(1,0,0,1, n) // 用尾端递回,和 scheme 相同
return whileLoop(n) // 改写成 javascript 的 while 循环
function square(n) {
return n*n
}
function isEven(n) {
if (n%2 == 0) return true
else return false
}
// while 循环
function whileLoop(n) {
var a = 1
var b = 0
var p = 0
var q = 1
var count = n
while (count != 0) {
console.log(a,b,p,q, count) // 展示用
if (isEven(count)) {
var nextP = square(p) + square(q)
var nextQ = 2*p*q + square(q)
p = nextP
q = nextQ
count /= 2
}
else {
var nextA = b*q + a*q + a*p
var nextB = b*p + a*q
a = nextA
b = nextB
count

Links booklink

Contact Us: admin [ a t ] ucptt.com