Other Clojure solutions.
(ns collatz-conjecture)
(defn- next-collatz-num [num]
(if
(even? num)
(/ num 2)
(+ 1 (* num 3))))
(defn- collatz-support [step-count num]
(cond
(= num 1) step-count
:else (let [next-num (next-collatz-num num)]
(collatz-support (+ 1 step-count) next-num))))
(defn collatz [num]
{:pre [(< 0 num)]}
(collatz-support 0 num))
Other Elm solutions.
module CollatzConjecture exposing (collatz)
countCollatzSteps : Int -> Int -> Int
countCollatzSteps steps n =
let
val =
if modBy 2 n == 0 then
n // 2
else
(3 * n) + 1
in
if n == 1 then
steps
else
countCollatzSteps (steps + 1) val
collatz : Int -> Result String Int
collatz start =
if start <= 0 then
Result.Err "Only positive numbers are allowed"
else
Result.Ok <| countCollatzSteps 0 start
Other Haskell solutions.
module CollatzConjecture (collatz) where
collatz' :: Integer -> Integer
collatz' 1 = 0
collatz' n =
let next = if even n then quot n 2 else 3 * n + 1
in succ $ collatz' next
collatz :: Integer -> Maybe Integer
collatz n
| n <= 0 = Nothing
| otherwise = Just $ collatz' n
Other Roc solutions.
module [steps]
steps : U64 -> Result U64 [InvalidInput]
steps = \n ->
if n < 1 then
Err InvalidInput
else
Ok (collatzCount 0 n)
collatzCount : U64, U64 -> U64
collatzCount = \stepCount, n ->
val =
if n % 2 == 0 then
(n // 2)
else
(3 * n + 1)
if n == 1 then
stepCount
else
collatzCount (stepCount + 1) val