Skip to content

Instantly share code, notes, and snippets.

@mac-chaffee
Forked from CMCDragonkai/dynamic_factorial.exs
Last active December 27, 2017 22:34
Show Gist options
  • Select an option

  • Save mac-chaffee/2d5200a4c8b0a08af44f6d185a2ca8d6 to your computer and use it in GitHub Desktop.

Select an option

Save mac-chaffee/2d5200a4c8b0a08af44f6d185a2ca8d6 to your computer and use it in GitHub Desktop.
Elixir: Tail Recursive Factorial - Avoids growing stack space linearly. This is related to dynamic programming: http://stackoverflow.com/q/12649970/582917
// factorial tail recursive (Elixir style)
// 4! means 1*2*3*4, we can ignore 1, which makes it 2*3*4 = 24
def factorial(num), do: factorial(num, 1)
defp factorial(num, _product) when num < 0, do: raise ArithmeticError
defp factorial(num, product) when num <= 1, do: product
defp factorial(num, product), do: factorial(num - 1, product * num)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment