Sum digits of an integer
Sum digits of an integer is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.
This task takes a Natural Number in a given Base and returns the sum of it digits:
- 1 sums to 1;
- 1234 sums to 10;
- 0xfe sums to 29;
- 0xf0e sums to 29.
C++
<lang cpp>
- include <iostream>
- include <cmath>
int SumDigits(const int digits, const int BASE = 10) { int sum = 0; int x = digits; for (int i = log(digits)/log(BASE); i>0; i--){ const int z = pow(BASE,i); const int t = x/z; sum += t; x -= t*z; } return x+sum; } int main() { std::cout << SumDigits(1) << ' ' << SumDigits(12345) << ' ' << SumDigits(123045) << ' ' << SumDigits(0xfe,16) << ' ' << SumDigits(0xf0e,16); } </lang> Produces:
1 15 15 29 29
Erlang
<lang erlang> -module(sum_digits). -export([sum_digits/2, sum_digits/1]).
sum_digits(N) ->
sum_digits(N,10).
sum_digits(N,B) ->
sum_digits(N,B,0).
sum_digits(0,_,Acc) ->
Acc;
sum_digits(N,B,Acc) when N < B ->
Acc+N;
sum_digits(N,B,Acc) ->
sum_digits(N div B, B, Acc + (N rem B)).
</lang>