Sum digits of an integer: Difference between revisions
Content added Content deleted
(added ruby) |
m (→{{header|C++}}: line too long (more than 100 chars)) |
||
Line 7: | Line 7: | ||
=={{header|C++}}== |
=={{header|C++}}== |
||
⚫ | |||
#include <iostream> |
<lang cpp>#include <iostream> |
||
#include <cmath> |
#include <cmath> |
||
int SumDigits(const int digits, const int BASE = 10) { |
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() { |
int main() { |
||
std::cout << SumDigits(1) << ' ' |
|||
<< SumDigits(12345) << ' ' |
|||
} |
|||
<< SumDigits(123045) << ' ' |
|||
</lang> |
|||
<< SumDigits(0xfe, 16) << ' ' |
|||
<< SumDigits(0xf0e, 16) << std::endl; |
|||
⚫ | |||
Produces: |
Produces: |
||
<pre> |
<pre> |
Revision as of 20:42, 19 July 2012
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) << std::endl;
}</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>
Ruby
<lang ruby>>> def sumDigits(num, base = 10) >> num.to_s(base).split(//).inject(0) {|z, x| z + x.to_i(base)} >> end => nil >> sumDigits(1) => 1 >> sumDigits(12345) => 15 >> sumDigits(123045) => 15 >> sumDigits(0xfe,16) => 29 >> sumDigits(0xf0e,16) => 29 </lang>