1 parent 6f71043 commit 8c04e7c66f49a794e0b08be51b123b3146a7d009 committed Sep 4, 2011
Showing with 63 additions and 2 deletions.
1. +0 −2 ex_1_015.scm
2. +22 −0 ex_1_016.scm
3. +24 −0 ex_1_017.scm
4. +17 −0 ex_1_018.scm
 @@ -3,8 +3,6 @@ (define (p x) (- (* 3 x) (* 3 (cube x)))) (define (sine angle) - (display "1") - (newline) (if (not (> (abs angle) 0.1)) angle (p (sine (/ angle 3.0)))))
 @@ -0,0 +1,22 @@ +(require rackunit) + +(define (square x) + (* x x)) + +(define (exponent b n) + (define (exp-iter b n a) + (cond ((= n 0) a) + ((even? n) (exp-iter (square b) + (/ n 2) + a)) + (else (exp-iter b + (- n 1) + (* a b))))) + (if (< n 0) + (/ 1 + (exp-iter b (- n) 1)) + (exp-iter b n 1))) + +(check-equal? (exponent 3 4) 81) +(check-equal? (exponent 3 3) 27) +(check-equal? (exponent 3 -1) 1/3)
 @@ -0,0 +1,24 @@ +(require rackunit) + +(define (double a) + (arithmetic-shift a 1)) + +(define (halve a) + (arithmetic-shift a (- 1))) + +(define (square a) + (* a a)) + +(define (* a b) + (if (= b 0) + 0 + (+ a (* a (- b 1))))) + +(define (fast-expt b n) + (cond ((= n 0) 1) + ((even? n) (square (fast-expt b (/ n 2)))) + (else (* b (fast-expt b (- n 1)))))) + + +(check-equal? (fast-expt 5 4) 625) +(check-equal? (fast-expt 3 3) 27)
 @@ -0,0 +1,17 @@ +(require rackunit) + +(define (double a) + (arithmetic-shift a 1)) + +(define (halve a) + (arithmetic-shift a (- 1))) + +(define (* a b) + (cond ((= b 0) 0) + ((even? b) (double (* a (halve b)))) + (else (+ a (* a (- b 1)))))) + +(check-equal? (* 5 4) 20) +(check-equal? (* 3 3) 9) +(check-equal? (* 10 27) 270) +