Skip to content

Instantly share code, notes, and snippets.

@venantius
Created September 9, 2018 10:02
Show Gist options
  • Save venantius/ff4ed7135c8a0802accd81bafe8c8313 to your computer and use it in GitHub Desktop.
Save venantius/ff4ed7135c8a0802accd81bafe8c8313 to your computer and use it in GitHub Desktop.
(ns down-to-zero.core)
(defn factorial
[i n factors]
(if (> i (Math/sqrt n))
;; we've found all the factors, return
factors
(if (zero? (mod n i))
;; this is a factor, add it, increment i, and recurse
(factorial (inc i) n (conj factors i (/ n i)))
;; this is not a factor, increment i and recurse
(factorial (inc i) n factors))))
(defn factor-cost
[n]
(let [f (factorial 1 n #{})
c (count f)]
(if (odd? c)
;; the number has an integer square root
(first (drop (Math/floor (/ c 2)) (sort f)))
;; the number doesn't have an integer square root; take the larger of its
;; two median factors
(second (drop (dec (Math/floor (/ c 2))) (sort f))))))
(defn cost-fn
[q]
(let [f-cost (factor-cost q)]
(if (< f-cost q)
;; using one of the factors has a cost of 1
(inc (cost-fn f-cost))
q)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment