From: Ramakrishnan Muthukrishnan Date: Tue, 4 May 2010 18:08:04 +0000 (+0530) Subject: solution for exercise 1.31 X-Git-Url: https://git.rkrishnan.org/pf/content/en/seg/about/%3C?a=commitdiff_plain;h=05861223c8e1d6aadec146a47a59140695380680;p=sicp.git solution for exercise 1.31 --- diff --git a/src/sicp/ex1_31.clj b/src/sicp/ex1_31.clj new file mode 100644 index 0000000..a1c8dd7 --- /dev/null +++ b/src/sicp/ex1_31.clj @@ -0,0 +1,43 @@ +(ns sicp.ex1_31 + (:use [clojure.contrib test-is] + [sicp utils])) + +(defn product [a b] + (if (> a b) + 1 + (* a (product (+ a 1) b)))) + +(defn prod [term a next b] + (if (> a b) + 1 + (* (term a) + (prod term (next a) next b)))) + +;; factorial +;; fact (n) = n * factorial (n - 1) + +(defn factorial [n] + (prod identity 1 inc n)) + +(deftest test-factorial-of-6 + (is (factorial 6) 720)) + +(deftest test-factorial-of-10 + (is (factorial 10) 3628800)) + +(defn prod-pi [a b] + (prod #(/ (* % (+ % 2)) (square (+ % 1.0))) a #(+ % 2) b)) + +(deftest test-pi-2-digits-accuracy + (is (> (Math/abs (- 3.14159 (* 4 (prod-pi 2 1000)))) 0.001) true)) + +(defn iter-prod [term a next b result] + (if (> a b) + result + (iter-prod term (next a) next b (* a result)))) + +(defn iprod [term a next b] + (iter-prod term a next b 1)) + +(deftest test-iprod-for-prod-of-1-to-10 + (is (iprod identity 1 inc 10) (prod identity 1 inc 10)))