Skip to content

Instantly share code, notes, and snippets.

@altphi
Created October 29, 2016 14:12
Show Gist options
  • Save altphi/d0bf16a20101217dde31904b8da01958 to your computer and use it in GitHub Desktop.
Save altphi/d0bf16a20101217dde31904b8da01958 to your computer and use it in GitHub Desktop.
3n + 1 problem
;; 3n + 1 problem
;; https://en.wikipedia.org/wiki/Collatz_conjecture
(defn threen
([n]
(threen n 0))
([n k]
(let [newK (if (>= n 1) (+ k 1) k)]
(if (= n 1)
newK
(if (even? n)
(threen (/ n 2) newK)
(threen (+ (* n 3) 1) newK))))))
(defn max-threen [i j]
(print i " " j " "
(apply max (map #(threen %) (range i j)))))
;;
(max-threen 1 10) ; 1 10 20
(max-threen 100 200 ; 100 200 125
(max-threen 201 210) ; 201 210 89
(max-threen 900 1000) ; 900 1000 174
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment