Skip to content

Instantly share code, notes, and snippets.

@jaye-ross
Last active December 16, 2019 19:36
Show Gist options
  • Save jaye-ross/11686bcbbe62b9c2b12bafc43e3dece4 to your computer and use it in GitHub Desktop.
Save jaye-ross/11686bcbbe62b9c2b12bafc43e3dece4 to your computer and use it in GitHub Desktop.
Create Collatz sequences
;; see https://www.quantamagazine.org/mathematician-terence-tao-and-the-collatz-conjecture-20191211/
;; for problem statement and definition of the sequence
(defn collatz [x]
(if (even? x) (/ x 2) (+ (* x 3) 1)))
(defn collatz-seq [x]
(lazy-cat [x] (collatz-seq (collatz x))))
;; test
(take 20 (collatz-seq 11))
;; user=> (take 20 (collatz-seq 11))
;; (11 34 17 52 26 13 40 20 10 5 16 8 4 2 1 4 2 1 4 2)
;; produce the collatz sequence and stop at 1
(defn collatz-stop-at-1 [x]
(let [cseq (collatz-seq x)]
(loop [fseq '() cseq cseq]
(if (= (first cseq) 1)
(reverse (conj fseq 1))
(recur (conj fseq (first cseq)) (rest cseq))))))
;; user=> (collatz-stop-at-1 511)
;; (511 1534 767 2302 1151 3454 1727 5182 2591 7774 3887 11662 5831 17494 8747 26242 13121
;; 39364 19682 9841 29524 14762 7381 22144 11072 5536 2768 1384 692 346 173 520 260 130 65
;; 196 98 49 148 74 37 112 56 28 14 7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment