Skip to content

Instantly share code, notes, and snippets.

@ppopoff
Created March 30, 2016 22:05
Show Gist options
  • Save ppopoff/92397b1dafeab7c2d03a2bf82c445799 to your computer and use it in GitHub Desktop.
Save ppopoff/92397b1dafeab7c2d03a2bf82c445799 to your computer and use it in GitHub Desktop.
Euler task 20
-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)).
@firegurafiku
Copy link

In fact, the following is not tail-recursive:

factorial_rec (N) -> factorial_rec(N - 1) * N.

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.

@ppopoff
Copy link
Author

ppopoff commented Apr 3, 2016

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