Another Project Euler problem:
2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number 2^1000?
Here ^ denotes exponentiation. And there’s the first rub. The Erlang math:pow/2 function returns a floating point approximation, so we need to code up an exact integer operation.
-module(mymath).
-export([pow/2]).
square(X) ->
X * X.
pow(_, 0) -> 1;
pow(N, 1) -> N;
pow(N,K) when K rem 2 == 0 -> square(pow(N, K div 2));
pow(N,K) -> N * pow(N, K-1).
Then we can call it from the command line:
21> D = integer_to_list(mymath:pow(2,1000)). "10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376"
My initial solution (wrong!) was
22> lists:sum(D). 15862
Recall that Erlang characters are really integers, where $0 == 48.
We just need an offset.
23> lists:sum(D) - length(D)*$0. 1366

Posts