add factorial

This commit is contained in:
Caleb Webber 2024-04-08 12:41:38 -04:00
parent f59363eaf6
commit cbe6ad7a00
2 changed files with 26 additions and 0 deletions

View file

@ -33,4 +33,26 @@ defmodule AoC.Util.Math do
def lcm(a, b) do
div(a * b, gcd(a, b))
end
@doc """
Returns the facorial of n.
iex> AoC.Util.Math.factorial(0)
1
iex> AoC.Util.Math.factorial(1)
1
iex> AoC.Util.Math.factorial(2)
2
iex> AoC.Util.Math.factorial(5)
120
iex> AoC.Util.Math.factorial(-1)
nil
"""
def factorial(0), do: 1
def factorial(1), do: 1
def factorial(n) when n < 0, do: nil
def factorial(n), do: factorial(n-1, n)
defp factorial(1, k), do: k
defp factorial(n, k), do: factorial(n-1, k*n)
end

4
test/util/math_test.exs Normal file
View file

@ -0,0 +1,4 @@
defmodule AoC.Util.MathTest do
use ExUnit.Case
doctest AoC.Util.Math
end