Faffing round the edges Its easier than getting stuck in

28Dec/080

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.

Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

You must be logged in to post a comment.

No trackbacks yet.

 

December 2008
M T W T F S S
« Nov   Mar »
1234567
891011121314
15161718192021
22232425262728
293031  

Archives