longest_collatz_sequence.gsp 870 B

1234567891011121314151617181920212223242526272829303132
  1. (ns main
  2. "fmt"
  3. "github.com/jcla1/gisp/core")
  4. (def main (fn []
  5. (let [[n (collatz-longest 1000000)]]
  6. (fmt/println "Longest sequence produced by:" n)
  7. (fmt/printf "It was %d elements long!\n" (collatz-length n))
  8. ())))
  9. (def collatz-longest (fn [below-val]
  10. (loop [[below below-val]
  11. [n 1.0]
  12. [max 0]]
  13. (if (= below 1) (+ 1 n)
  14. (let [[l (collatz-length below)]
  15. [m (+ -1 below)]]
  16. (if (> l max)
  17. (recur m (assert float64 below) (assert int l))
  18. (recur m n max)))))))
  19. (def collatz-length (fn [n]
  20. (loop [[next n]
  21. [acc 1]]
  22. (if (= next 1)
  23. acc
  24. (recur (collatz-next next) (int (+ acc 1)))))))
  25. (def collatz-next (fn [n]
  26. (if (= 0 (mod n 2))
  27. (* 0.5 n)
  28. (+ 1 (* 3 n)))))