solutions/Structure and Interpretatio.../sicp-ex-1.17.rkt

43 lines
887 B
Racket
Raw Permalink Normal View History

2024-04-16 19:13:00 -04:00
(define (multiply a b)
(define (iter a b product)
(if (= b 0)
product
(iter a (- b 1) (+ product a))))
(iter a b 0))
; multiply
(define (sqr n)
(multiply n n))
(define (divide a b)
(define (iter a b product)
(cond ((= a 0) product)
((< a 0) (- product 1))
(else (iter (- a b) b (+ product 1)))))
(iter a b 0))
; divide
(define (halve a)
(divide a 2))
(define (fast-ext number power)
(define (iter number power product)
(cond ((= power 0) product)
((even? power) (iter (sqr number)
(halve power)
product))
(else (iter number
(- power 1)
(multiply number product)))))
(iter number power 1))
; fast-ext
(fast-ext 5 3)
(fast-ext 2 2)
(fast-ext 1 2)
(fast-ext 9 4)
(fast-ext 2 0)
(fast-ext 7 1)