This commit is contained in:
NaiJi ✨ 2020-08-21 17:48:12 +03:00
parent ca2a636675
commit 9de52ba145
1 changed files with 43 additions and 0 deletions

43
sicp-ex-1.17.rkt Normal file
View File

@ -0,0 +1,43 @@
(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)