]> git.rkrishnan.org Git - sicp.git/blobdiff - src/sicp/utils.clj
solution to 4.43
[sicp.git] / src / sicp / utils.clj
index 6ebbe2463555d06e18709a7cc9ca27ee2618233e..516b0141eba9306c16ded1167c800cb8d5407110 100644 (file)
@@ -2,7 +2,7 @@
 
 (defn square [x] (* x x))
 
-(defn myabs
+(defn abs
   "find absolute value of x"
   [x]
   (if (< x 0) (- x) x))
 (defn half [x]
   (/ x 2))
 
+(defn divides? [a b]
+  (= (rem b a) 0))
+
+(defn- find-divisor [n test-divisor]
+  (cond (> (square test-divisor)  n) n
+       (divides? test-divisor n) test-divisor
+       :else (find-divisor n (inc test-divisor))))
+
+(defn- smallest-divisor [n]
+  (find-divisor n 2))
+
+(defn prime? [n]
+  (= (smallest-divisor n) n))
+
+(defn gcd [a b]
+  (if (= b 0)
+    a
+    (gcd b (rem a b))))
+
+(defn average [ & coll]
+  (/ (reduce + coll)
+     (float (count coll))))
+
+(defn approx-equal [x y]
+  (< (abs (- x y)) 0.00001))
+
+(defn error [^String string]
+  (throw (Exception. string)))
+
 (defmacro microbench
   " Evaluates the expression n number of times, returning the average
     time spent in computation, removing highest and lowest values.