Created
March 30, 2016 22:05
-
-
Save ppopoff/92397b1dafeab7c2d03a2bf82c445799 to your computer and use it in GitHub Desktop.
Euler task 20
This file contains 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
-module(euler20). | |
-export([solve/1]). | |
%% the solution for the problem | |
solve (N) -> sum_digits(factorial_rec(N), 0). | |
%% Tail recursive implementation | |
%% of the factorial function | |
%% Question: I think that it's much faster than | |
%% the second implementation. Is it correct? | |
factorial_rec (0) -> 1; | |
factorial_rec (1) -> 1; | |
factorial_rec (N) -> factorial_rec(N - 1) * N. | |
%% yet another implementation | |
%% I was using list:seq that reminds me of | |
%% ranges in other languages | |
factorial_lst (N) -> | |
lists:foldl(fun(Curr, Prod) -> Curr * Prod end, 1, lists:seq(1, N)). | |
%% Finds a summ of the digits | |
sum_digits (N, 0) -> | |
sum_digits(N div 10, N rem 10); | |
sum_digits (0, Sum) -> Sum; | |
sum_digits (N, Sum) -> | |
sum_digits(N div 10, Sum + (N rem 10)). |
First is not tail recursive, yes. But it will be faster
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In fact, the following is not tail-recursive:
The second approach is going to be faster if Erlang supports lazy lists (or, at least, enumerators) and doesn't really allocate space for each item in
list:seq
.