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.
fact
finds 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?