SICP:对数步数内迭代计算幂的函数
在SICP 32(48)页
根据书中给出的关系 (bn/2)2=(b2)n/2 ,并且使用一个不变量记录中间结果,写出对数步数内迭代计算幂的函数:
方法一(not me):
;;; 16-fast-expt.scm (define (fast-expt b n) (expt-iter b n 1)) (define (expt-iter b n a) (cond ((= n 0) a) ((even? n) (expt-iter (square b) (/ n 2) a)) ((odd? n) (expt-iter b (- n 1) (* b a)))))
方法二(me):
#lang racket (define (fast-expt b n) (cc b 1 n) );define (define (cc b a n) (cond ((= n 0) a);0 ((= n 1) (* b a)) ((even? n) (cc (square b) (square a) (/ n 2));cc );1 (else (* b (cc b a (- n 1)) );* );else );cond );define (define (cc-new b a n) (cond ((= n 0) a);0 ((even? n) (cc-new (square b) a (/ n 2)));even (else (cc-new b (* b a) (- n 1)));else );cond );define (define (fast-expt-new b n) (cc-new b 1 n) );define (define (even? n) (= (remainder n 2) 0);= );define (define (square x) (* x x)) (fast-expt-new 2 1) (fast-expt-new 2 2) (fast-expt-new 2 3) (fast-expt-new 2 4) (fast-expt-new 2 5) (fast-expt-new 2 10)
posted on 2015-03-21 13:19 Zachary_wiz 阅读(189) 评论(0) 编辑 收藏 举报