1
\$\begingroup\$

This is a problem in poject Euler:

n! means n × (n − 1) × ... × 3 × 2 × 1

For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800, and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.

Find the sum of the digits in the number 100!

I decided to solve it using erlang. This is what I've come up with.

-module(fact).
-compile(export_all).

fact(1) -> 1;
fact(N) -> N*fact(N-1).

tolist(N) when N < 10 -> [N];
tolist(N) when N >= 10 -> tolist(N div 10)++[N rem 10].

sum(List) -> sum(List, 0).
sum([H|T], C) -> sum(T, C + H);
sum([], C) -> C.

factfinds the factorial of the number. toList converts it to a list of integers and sum gets the sum of the integers in the list. I run this program like this:

fact:sum(fact:tolist(fact:fact(100))).

Do I have to use 3 functions? Is there a problem with me doing so?

Should I make another function that calls all 3 functions?

\$\endgroup\$
0
\$\begingroup\$

Don't need rewrite functions which already exist in standard library. Almost always it's will give worse result and just take away your time for writing and testing.

  1. For converting from integer to list (string) - integer_to_list/1

  2. For getting some single result from set data in a list - use lists:foldl/3

  3. For extracting the numerical value from digit symbol - just subtract zero-value($0, number representation in Erlang).

So, if accumulate all of this points, get:

task_(N)->
lists:foldl(fun(X,Sum)->Sum+X-$0 end,0,integer_to_list(fact(N))).

If saying generally, I don't see any problem in rule - "one function for one task". It will make your code more readable, flexible and good for testing.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.