Skip to content

Instantly share code, notes, and snippets.

@dexterous
Last active February 26, 2023 14:33
Show Gist options
  • Save dexterous/7f5c6741de321396fd7e7a60f3d039e8 to your computer and use it in GitHub Desktop.
Save dexterous/7f5c6741de321396fd7e7a60f3d039e8 to your computer and use it in GitHub Desktop.
(defn how-not-to-factorial [x]
(condp #(< %2 %1) x
1 (throw (IllegalArgumentException.))
3 x
(loop [acc (bigint x) prev (dec x)]
(if (= prev 2) (* acc 2) (recur (* acc prev) (dec prev))))))
;; when you want to factorial...
(defn just-factorial [n] (apply * (range 1N (inc n))))
(require '[clojure.string :as s])
(defn- fn-name [f]
(-> f
class
(.getName)
(s/split #"\$")
last))
(doseq [fac [how-not-to-factorial just-factorial]]
(let [n 65 bench-cycles 10000]
(println (s/join [(fn-name fac) "(" n ")"]))
(println (s/join (repeat 25 "=")))
(print "Single run: ")
(time (fac n))
(print " Benchmark: ")
(time (dotimes [_ bench-cycles] (fac n)))
(print " Result: ")
(println (fac n))
(println)))
@dexterous
Copy link
Author

Executable version of (updated) code available at https://replit.com/@dexterous/simplicate-dont-complify

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment