;recursion (define (expt b n) (if (= n 0) 1 (* b (expt b (- n 1))))) ;iteration (define (expt b n) (expt-iter b n 1))
(define (expt-iter b counter product) (if (= counter 0) product (expt-iter b (- counter 1) (* b product))))
;Θ(log n) recursion (define (fast-expt b n) (cond ((= n 0) 1) ((even? n) (square (fast-expt b (/ n 2)))) (else (* b (fast-expt b (- n 1)))))) ;Θ(log n) iteration (define (expt-iter b count product) (cond ((= count 0) product) ((even? count) (expt-iter (square b) (/ count 2) product)) (else (expt-iter b (- count 1) (* b product)))))
6. 최대 공약수
(define (gcd a b) (if (= b 0) a (gcd b (remainder a b))))
7. 소수판별
;general (define (divides? a b) (= (remainder b a) 0))
(define (smallest-divisor n) (find-divisor n 2))
(define (find-divisor n test-divisor) (cond ((> (square test-divisor) n) n) ((divides? test-divisor n) test-divisor) (else (find-divisor n (+ test-divisor 1)))))
(define (prime? n) (= n (smallest-divisor n))) ;Fermat (define (expmod base exp m) (cond ((= exp 0) 1) ((even? exp) (remainder (square (expmod base (/ exp 2) m)) m)) (else (remainder (* base (expmod base (- exp 1) m)) m))))
(define (fermat-test n) (define (try-it a) (= (expmod a n n) a)) (try-it (+1 (random (- n 1)))))
(define (fast-prime? n times) (cond ((= times 0) #t) ((fermat-test n) (fast-prime? n (- times 1))) (else#f)))
8. 수열의 덧셈
(define (sum term a next b) (if (> a b) 0 (+ (term a) (sum term (next a) next b))))
9. 이분법
(define (half-interval-method f a b) (let ((a-value (f a)) (b-value (f b))) (cond ((and (negative? a-value) (positive? b-value)) (search f a b)) ((and (negative? b-value) (positive? a-value)) (search f b a)) (else (error"Values are not of opposite sign" a b)))))