码迷,mamicode.com
首页 > 其他好文 > 详细

SICP:反复用加法来实现乘法 1.17

时间:2015-03-21 15:22:18      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:

#lang racket

(define (fast-multiplication a b n);a*n
  (cond ((= n 0) b);n==0
    ((even? n)
     (fast-multiplication (double a)
                  b
                  (halve n)));even? n
    (else
     (fast-multiplication a
                  (+ a b)
                  (- n 1))
     );else

    );cond
  );fast-multiplication  its iteration

(define (fast-multiplication-new a n)
  (cond ((= n 0) 0)
    ((= n 1) a)
    ((even? n) (double (fast-multiplication-new a
                        (halve n))))
   
    (else (a +
         (fast-multiplication-new a 
                      (- n 1)))
     );else
   );cond
  );fast-multiplication-new its recursive

(define (double x)
  (+ x x));double

(define (halve x)
  (/ x
     2)
  );halve

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


(fast-multiplication-new 8 0 1)
(fast-multiplication-new 8 0 2)
(fast-multiplication-new 8 0 3)
(fast-multiplication-new 8 0 4)
(fast-multiplication-new 8 0 9)

 

SICP:反复用加法来实现乘法 1.17

标签:

原文地址:http://www.cnblogs.com/wizzhangquan/p/4355571.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!