Forked from CMCDragonkai/dynamic_factorial.exs
Last active
December 27, 2017 22:34
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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