# cosmin/sicp-scheme

added exercises 1.15, 1.16, 1.17, 1.18

1 parent 84f4101 commit fde4478f5900c2210cf662eacba93e9d797c2b17 committed Feb 12, 2012
Showing with 77 additions and 0 deletions.
1. +19 −0 exercise-1-15.ss
2. +21 −0 exercise-1-16.ss
3. +19 −0 exercise-1-17.ss
4. +18 −0 exercise-1-18.ss
 @@ -0,0 +1,19 @@ +(define (cube x) (* x x x)) + +(define (p x) + (pretty-print 1) + (- (* 3 x) (* 4 (cube x)))) + +(define (sine angle) + (if (not (> (abs angle) 0.1)) + angle + (p (sine (/ angle 3.0))))) + + +;; each time we divide the angle by 3 until the angle is <= 0.1 +;; +;; 12.15 => 4.05 => 1.35 => 0.45 => 0.15 => 0.05 +;; +;; therefore we call p 5 times to compute sine of 12.15 + +;; both the space and complexity of this operation is log(n) (base 3)
 @@ -0,0 +1,21 @@ +(define (square x) (* x x)) + +(define (even? n) (= (remainder n 2) 0)) + +;; linear recursive algorithm + +(define (fast-expt b n) + (cond ((= n 0) 1) + ((even? n) (square (fast-expt b (/ n 2)))) + (else (* b (fast-expt b (- n 1)))))) + + +;; iterative algorithm + +(define (expt b n) + (fast-expt-iter b n 1)) + +(define (fast-expt-iter b n a) + (cond ((= n 0) a) + ((even? n) (fast-expt-iter (square b) (/ n 2) a)) + (else (fast-expt-iter b (- n 1) (* b a)))))
 @@ -0,0 +1,19 @@ +(define (mul a b) + (if (= b 0) + 0 + (+ a (mul a (- b 1))))) + +;; pretend the following are built-in + +(define (double a) (* a 2)) + +(define (halve a) (/ a 2)) + +(define (even? n) (= (remainder n 2) 0)) + +;; fast-multiplication -- log(n) steps + +(define (fast-mul a b) + (cond ((= b 0) 0) + ((even? b) (fast-mul (double a) (halve b))) + (else (+ a (fast-mul a (- b 1))))))
 @@ -0,0 +1,18 @@ +;; pretend built-ins + +(define (double a) (* a 2)) + +(define (halve a) (/ a 2)) + +(define (even? n) (= (remainder n 2) 0)) + + +;; iterative fast-mul + +(define (mul a b) + (fast-mul-iter a b 0)) + +(define (fast-mul-iter a b acc) + (cond ((= b 0) acc) + ((even? b) (fast-mul-iter (double a) (halve b) acc)) + (else (fast-mul-iter a (- b 1) (+ acc a)))))