Skip to content

Instantly share code, notes, and snippets.

@ponkore
Created March 25, 2012 12:09
Show Gist options
  • Save ponkore/2193213 to your computer and use it in GitHub Desktop.
Save ponkore/2193213 to your computer and use it in GitHub Desktop.
Calculate factorial
;; calculate elapsed time
(defmacro tm [form]
`(let [t# (System/currentTimeMillis)]
(do
(~@form)
(- (System/currentTimeMillis) t#))))
;; call 4 version of fact-* 10 times x 5 loop
(dotimes [i 5]
(println "fact-call: " (tm (dotimes [n 10] (fact-call 10000))))
(println "fact-loop: " (tm (dotimes [n 10] (fact-loop 10000))))
(println "fact-reduce: " (tm (dotimes [n 10] (fact-reduce 10000))))
(println "fact-apply: " (tm (dotimes [n 10] (fact-apply 10000)))))
;; results
;; faster -> slower
;; fact-call -> {fact-apply|fact-reduce} -> fact-loop
;; recursive call version
(defn fact-call [n]
(if (zero? n) 1
(*' n (fact-call (dec n)))))
;; loop & recur pattern version
(defn fact-loop [n]
(loop [result 1 cnt n]
(if (zero? cnt) result
(recur (*' result cnt) (dec cnt)))))
;; sequence 1..n and * (reduce)
(defn fact-reduce [n]
(reduce *' (take n (iterate inc 1))))
;; sequence 1..n and * (apply *)
(defn fact-apply [n]
(apply *' (take n (iterate inc 1))))
;;;user=> (fact-call 0)
;;;1
;;;user=> (fact-loop 0)
;;;1
;;;user=> (fact-reduce 0)
;;;1
;;;user=> (fact-apply 0)
;;;1
;;;user=> (fact-call 1)
;;;1
;;;user=> (fact-loop 1)
;;;1
;;;user=> (fact-reduce 1)
;;;1
;;;user=> (fact-apply 1)
;;;1
;;;user=> (fact-call 10)
;;;3628800
;;;user=> (fact-loop 10)
;;;3628800
;;;user=> (fact-reduce 10)
;;;3628800
;;;user=> (fact-apply 10)
;;;3628800
;;;user=>
fact-call: 1503
fact-loop: 3070
fact-reduce: 2721
fact-apply: 2666
fact-call: 1288
fact-loop: 3056
fact-reduce: 2708
fact-apply: 2722
fact-call: 1307
fact-loop: 3062
fact-reduce: 2709
fact-apply: 2698
fact-call: 1295
fact-loop: 3076
fact-reduce: 2676
fact-apply: 2686
fact-call: 1263
fact-loop: 3045
fact-reduce: 2697
fact-apply: 2644
nil
fact-call: 1503 1288 1307 1295 1263
fact-loop: 3070 3056 3062 3076 3045
fact-reduce: 2721 2708 2709 2676 2697
fact-apply: 2666 2722 2698 2686 2644
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment