This is my Clojure solution to Chapter 1, Exercise 21:
(ns sicp.ch1.ex21
(:require [sicp.ch1.ex16 :as sicp-ch1-ex16]))
(defn find-divisor
[n test-divisor]
(cond (> (sicp-ch1-ex16/square test-divisor) n) n
(zero? (rem n test-divisor)) test-divisor
:else (find-divisor n (inc test-divisor))))
(defn smallest-divisor
[n]
(find-divisor n 2))
(smallest-divisor 199) ; => 199
(smallest-divisor 1999) ; => 1999
(smallest-divisor 19999) ; => 7
(ns sicp.ch1.ex21
(:require [sicp.ch1.ex16 :as sicp-ch1-ex16]))
(defn find-divisor
[n test-divisor]
(cond (> (sicp-ch1-ex16/square test-divisor) n) n
(zero? (rem n test-divisor)) test-divisor
:else (find-divisor n (inc test-divisor))))
(defn smallest-divisor
[n]
(find-divisor n 2))
(smallest-divisor 199) ; => 199
(smallest-divisor 1999) ; => 1999
(smallest-divisor 19999) ; => 7
No comments:
Post a Comment