сollatz-сonjecture

This commit is contained in:
2024-06-26 23:06:52 -04:00
parent 4c3da6abe4
commit b62fcbc5ea
10 changed files with 266 additions and 0 deletions

View File

@@ -0,0 +1,15 @@
defmodule CollatzConjecture do
@doc """
calc/1 takes an integer and returns the number of steps required to get the
number to 1 when following the rules:
- if number is odd, multiply with 3 and add 1
- if number is even, divide by 2
"""
@spec calc(input :: pos_integer()) :: non_neg_integer()
def calc(input) when is_integer(input) and input > 0, do: collatz(input)
defp collatz(input, steps \\ 0)
defp collatz(1, steps), do: steps
defp collatz(input, steps) when rem(input, 2) == 0, do: collatz(div(input, 2), steps + 1)
defp collatz(input, steps), do: collatz(input * 3 + 1, steps + 1)
end