2008. 3. 4.

연습문제 1.16

b^n을 구할 때 n 이 짝수인 경우와 n이 홀수인 경우를 나누면 된다.
짝수인 경우는 다음 단계에 넘길 수는 현재 단계 밑수의 제곱과 그 단계수를 1/2로 나눈수면 된다.
따라서

(define (fast-expt b n)
  (define (fast-expt-iter b counter product)
    (cond ((= counter 0) product)
          ((even? counter) (fast-expt-iter (* b b)
                                     (/ counter 2)
                                     product))
          (else (fast-expt-iter b
                                (- counter 1)
                                (* product b)))))
  (fast-expt-iter b n 1))
가 된다.

댓글 없음:

댓글 쓰기