Tuesday, January 20, 2009

Erlang solution for Euler problem 16

In project Euler problem number 16 we are asked to sum the digits of the number 2^1000.

The Erlang solution for this one is trivial, thanks to the arbitrary precision integer support in Erlang:

%% Project Euler, problem 16
%%
%% What is the sum of the digits of the number 2^1000?

-module(euler16).
-author('Cayle Spandon').

-export([solve/0, solve/1]).

power_of_2(N) ->
1 bsl N.

digits_sum(N) ->
if
N < 10 ->
N;
true ->
(N rem 10) + digits_sum(N div 10)
end.

solve() ->
solve(1000).

solve(N) ->
digits_sum(power_of_2(N)).

1 comment:

Buzz de Cafe said...

Here's mine:

lists:foldl(fun(X, Acc)-> (X-48) + Acc end, 0, integer_to_list(1 bsl 1000)).

why X-48? to convert ASCII to numerical value.