Problem 16: Sum of digits
I realised that you can sort the Project Euler problems by difficulty. So I did. Which is why the order gets a bit odd from now onwards. I have no time to do Euler problems so I am cherry picking what I can fit into the spare 5 and 10 minute slots I have. So...problem 16:
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 21000?
Not a lot to say really so just the code.
prob16(N, Exp) -> sum_the_digits(round(math:pow(N, Exp))). sum_the_digits(N) -> L = integer_to_list(N), lists:foldl(fun(X, Acc) -> Acc + list_to_integer([X]) end, 0, L).
The second function (integer_to_list) turns a number into a list of its digits and then folds the list to sum the digits. Can't just use lists:sum as each list element is now a "String" so needs to be turned back into an integer with list_to_integer([X]). This reeks of hack so if anyone knows a better way please let me know.