# Count sum of all digits

This challenge is to write a program or script which counts the sum of all digits within the integers from 1 up to and including a given number.

Input, one positive integer. Output, the sum of digits in that number and all smaller numbers.

Examples:

Input: 5
Integer Sequence: 1, 2, 3, 4, 5
Sum of Digits: 1 + 2 + 3 + 4 + 5 = 15

Input: 12
Integer Sequence: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12
Sum of Digits: 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 1 + 0 + 1 + 1 + 1 + 2 = 51


To be clear, this is to count a sum of the digits - not the integers. For single-digit inputs, this will be the same. However, inputs larger than 10 will have different responses. This would be an incorrect response:

Input: 12
Output: 78


Another example, to show the difference:

Input: 10

Integer Sequence: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Sum of Integers (INCORRECT RESPONSE): 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55

Digit Sequence: 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 0
Sum of Digits (CORRECT RESPONSE): 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 1 + 0 = 46


A larger test case (CORRECT RESPONSE):

Input: 1000000
Output: 27000001


Rules & Guidelines:

• Submitted code must be a complete program or script - not just a function. If the code requires includes, imports, etc., they must be included in the posted code.
• The number must be input by the user - not hard-coded. Input may be received as a command-line argument, file, stdin, or any other means by which your language can take user input.
• The code must be able to properly handle inputs at least up to (2^64)-1.
• The code should only output the sum.
• Submitted programs & scripts should be user-friendly and not wasteful of computer resources (e.g.: they should not declare insanely-large arrays to hold every character). There is no strict bonus or penalty for this, but please be good programmers.

Scoring:

Primary scoring mechanism is by code length. Lower scores are better. The following bonuses and penalties also apply:

• -25 Bonus if your code can handle all positive numbers, for example: 1234567891234567891234564789087414984894900000000
• -50 Bonus if your code can handle simple expressions, for example 55*96-12. To qualify for this bonus, the code should handle + - / * (addition, subtraction, division, multiplication) operators and enforce order of operations. Division is regular integer division.
• The given example (55*96-12) evaluates to 5268. Your code should return the same for either of those inputs - correct answer is 81393.
• -10 Bonus if your code qualifies for the -50 bonus and can handle the ^ (exponent) operator.
• -100 Bonus if your code qualifies for the -50 bonus and does not use eval or similar to handle expressions.
• +300 Penalty if your code relies upon any web resources.
• And what should 55*96-12 return? Commented Jan 15, 2014 at 18:04
• Bonuses may be a bit on the big side, seems to be becoming a competition on the biggest negative score :) Commented Jan 15, 2014 at 19:12
• @ST3 if it's virtually impossible to win without the bonuses, then it's almost better to just make them requirements, or be worth less. Commented Jan 15, 2014 at 19:17
• @flonk: This is wrong. Why people don't read tasks, I wonder. I decided to put a note in task (as an edit). Seriously, this is not task about summing numbers.
– null
Commented Jan 16, 2014 at 12:35
• -1 because this challenge uses the outdated (and awful) scoring incentive of "bonuses". Commented May 9, 2018 at 21:23

### Python (brute force solution)

f = lambda x: sum( sum( int(k) for k in str(i) ) for i in xrange(1, x+1) )

>>> f(12)
51
>>> f(5)
15


### Python (a more elegant solution)

a = lambda x: all(i=='9' for i in x)
l = lambda x: int(x) if a(x) else 10**(len(x) -1 )- 1
s = lambda i: 45*(i*(10**(i-1)))
f = lambda k:s( len(k) - (0 if a(k) else 1 ) ) + f( str(int(k) - l( k )) ) if len( k ) > 1 else sum( xrange(1, int(k)+1) )

>>> f('12')
51
>>> f('5')
15

• The question says Submitted code must be a complete program or script - not just a function. If the code requires includes, imports, etc., they must be included in the posted code.
– Wasi
Commented Jan 16, 2014 at 18:53

# APL: 12 characters (18 octects of UTF-8), no bonuses

      +/,(16⍴10)⊤⍳


Examples:

      +/,(16⍴10)⊤⍳5
15
+/,(16⍴10)⊤⍳12
51
+/,(16⍴10)⊤⍳1000000
27000001
+/,(16⍴10)⊤⍳(55×96)-12
81393
+/,(16⍴10)⊤⍳(55×96*2)-12
12396621


It allows expressions, similarly to Mathematica solution, but it doesn't qualify for −50−10 bonuses as it requires + - ÷ × * rather than + - / * ^ and doesn't enforce the ‘correct’ order of operations.

# Haskell, 58-25 = 33

Similar to Vektorweg's answer (but a little more 'golfed').

main=readLn>>=print.sum. \x->[1..x]>>=map(read.(:[])).show


Ruby :(69 - 25 - 30) = 14

p (0..eval(ARGV[0])).flat_map{|i|i.to_s.chars.map(&:to_i)}.reduce(:+)


This handle operations, and can deal with any arbitraty number size.

# Javascript (82 - 50) = 32

The following fulfills all of the criteria and gets an -50 point bonus for handling basic arithmetic operations. Any suggestions would be appreciated.

r=0;for(i=eval(prompt());i>0;i--)for(j=i;j>=1;j=Math.floor(j/10))r+=j%10;alert(r);


I will try to make a more efficient algorithm that doesn't require lots of looping, but until then I will stick with this answer.

VB.net

Module z

Sub Main
Console.WriteLine( Enumerable.Range(1L,Integer.Parse(Console.ReadLine)).Sum(Function(n) n.ToString.Sum(Function(c) Int64.Parse(c))))
End Sub

End Module


## Haskell 49 (74 - 25)

main=interact$show.sum.map fromEnum.foldr(++)"".map show.enumFromTo 1.read  Handles all positive numbers (barring if the sum of digits exceed maxBound :: Int.) Does not handle expressions of any kind. Usage: echo$NUMBER | this-program

## Ruby 33 = 93 - 50 - 10

p (1..%x[echo #{ARGV[0]}|bc].to_i).reduce(0){|a,x|a+x.to_s.each_byte.reduce{|c,d|c+d-48}-48}


Usage ruby scriptname 1+1. Uses semi-standard utility programme bc for the calculations.

## Haskell (156 - 25 - 50 - 10 = 71)

import Data.Char
w=fromIntegral
q=w.digitToInt
e=sum
a(x:[])=e[1..q x]
a(x:y)=let p=w.length$y;f=q x in 45*10^(p-1)*p*f+10^p*e[1..f-1]+f*read y+f+a y  Counted bytes: > wc -m solution.hs 150 solution.hs  I added 6 bytes for the call: > a.show$ ...


-25:

> a.show$1234567891234567891234564789087414984894900000000 265889343871444899381999757086453238874482500000214  -50: > a.show$55*96-12
81393


-10:

> a.show$12^2 1215 > a.show$144
1215


I did this as an exercise, since I'm new to haskell. Maybe someone finds better/shorter ways to do the same...

PHP 5.3.6 112: 112

This is my first every code golf so let me know if I could do better or if I've added up wrong.

echo S(1200000);
function S($T){$S=0;for($i=1;$i<=$T;$i++){for($j=1;$j<=strlen($i);$j++){$t=(string)$i;$S+=$t[$j-1];}}return$S;}


I wasn't sure if the line echo S(120000) should be included in the calculation.

Not very fast, I'm still waiting on it to finish maxint.

*Update * I killed the process to calculate for 2 billion I calculated it would take about 3 hours, I'll see if I can speed it up.

A little faster now, but longer.

Using PHP

Here Input is taken using GET from variable input $_GET["input"]. <?php$a=0;for($b=1;$b<=$_GET["input"];$b++){$c=str_split($b);foreach($c as$d)$a+=$d;}echo $a;  DELPHI / PASCAL ( can only handle integer inputs) program t; {$APPTYPE CONSOLE}

uses SysUtils;

var a,i: Integer;
f: real;
sum : integer;
function cs ( i : Integer) : Integer;
var j : integer; t: string;
begin
result := 0;
t:=IntToStr(i);
for j := 1 to length(t) do
result := result + StrToInt(t[j]);

end;
begin
for i := 1 to a do
sum := sum + cs(i);
writeln(sum);
end.


# Bash+coreutils, 32 bytes, -25, -50, -10 bonuses; total -53

seq bc|fold -1|paste -s -d+|bc

• The first bc evals the passed in expression (including ^ for exponentiation)
• seq generates integers 1 to the result of the expression
• fold -1 splits each digit out - one digit per line
• paste joins the lines with a +
• bc evaluates the resulting expressiom

Large inputs should work, but will likely take a very long time.

I don't think I can take the -100 bonus, because using bc to evaluate expressions is effectively an eval.

### Output:

$./countalldigits.sh <<< 5 15$ ./countalldigits.sh <<< 10
46
$./countalldigits.sh <<< 12 51$ ./countalldigits.sh <<< "1002"
13506
$./countalldigits.sh <<< "2+10^3" 13506$ ./countalldigits.sh <<< 1000000
27000001
$ Groovy (2.3.6), 188 class T { public static void main(String[] a) { def s = new Scanner(System.in), t = s.nextLong(), j = 0, d = [] for (def i = 0; i <= t; i++) { d.add(i.toString().split('(?<=.)')) } d.flatten().each{j+=it.toLong()} print(j) } }  # k (-32 = 18 - 50) (?) expression input is in q/k syntax, which uses % for division, not /, and has APL-style "precedence" (which is to say none at all)—i.e. 55*96-12 is 4620, not 5268. additionally subject to various qualifications common to q/k programs due to the nature of the interpreter—the program as written and invoked allows the welcome banner to print (but to stderr, not stdout) and leaves the interpreter running. both can be avoided by invoking with closed stdin (i.e. <&- or </dev/null). probably doesn't work on 2^64-1, which is a reserved value in q/k flagrantly violates resource recommendations; i am not responsible if you crash your machine by testing it on 2^40 or something! % cat s.k +/.:',/$1+!.*.z.x
% ls -l s.k
-rw-------  1 adavies  staff  18 Jan 22 22:49 s.k
% q s.k 1000000
KDB+ 3.1 2013.12.27 Copyright (C) 1993-2013 Kx Systems
m32/ 16()core 8192MB adavies pro.local 192.168.2.103 PLAY 2014.03.27

27000001
q)\\
% q s.k '(55*96)-12'
KDB+ 3.1 2013.12.27 Copyright (C) 1993-2013 Kx Systems
m32/ 16()core 8192MB adavies pro.local 192.168.2.103 PLAY 2014.03.27

81393
q)\\
%

• Well if it uses % then you do not get 50 bonus, however you can slightly increase code size and get bonus.
– ST3
Commented Jan 23, 2014 at 9:03

# Brainfuck 12 Chars / Points

,[[>+>+<<-]>[-<+>]<-].


However this solution only handles numbers to 256-1

And you have to enter as I symbols. E.g.: 0 > 48; 1 > 49

A simple conversion would be

,>++++++++[<------>-]<[[>+>+<<-]>[-<+>]<-].


Breakdown:

,[[>+>+<<-]>[-<+>]<-].
,                       #Take user input
[                      #While the input number is still > 0
[>+>+<<-]             #Move it to the two next slots
>[-<+>]      #And copy it back in the first slot
<-]   #Decrease the input by 1 and repeat
.  #Print out result

The Number in third slot will constantly be added to


Python 3, 101-85: 16

Not the best answer, but this is my first attempt at an answer

a=[] for x in range(eval(input())+1):for z in str(x):a.append(int(z)) for v in a[1:-1]:a[0]+=v print(a[0])

That code a) wasn't syntactically correct and b) didn't get the correct answer.

This version does work though

a=[]
for x in range(eval(input())+1):
for z in str(x):a.append(int(z))
for v in a:a[0]+=v
print(a[0])


I've realised that by setting no starting point on the range for x, it starts at 0, meaning when I add v to the array 0+0 = 0 so it doesn't actually make a difference. And it also saves a few bytes

• Hi, welcome to the site! I'm counting 106 bytes, not 95. Are you sure you counted it right? Also, you could make it little bit shorter by doing x=1;exec"for z in str(x):a.append(int(z));x+=1;"*eval(input()) on line 2. Commented Jun 13, 2016 at 16:10
• @DrGreenEggsandIronMan thanks for the tip! Sorry I didn't realise you should include the spaces Commented Jun 13, 2016 at 16:54

# JavaScript (ES7), 64 - (50 + 10) = 4

n=>eval([...[...Array(eval(n))].map((_,i)=>i+1).join].join+)


The syntax for exponentiation is ** in ES7. If not for the -10 bonus, this would be valid ES6.

## Test Suite

f=n=>eval([...[...Array(eval(n))].map((_,i)=>i+1).join].join+)
e=s=>${s} =>${eval(s[0])} // template tag for test formatting
console.log(ef(5))
console.log(ef(12))
console.log(ef(10))
console.log(ef(1000000))
console.log(ef('55*96-12'))

# Haskell, 55 - (25+50+100)= -120

I don't know if this counts, but here goes:

d 0=0;d n=mod n 10 + d (div n 10);s 0=0;s n=d n+s (n-1)


and now the readable version (d stands for btd and s for sum'):

btd 0 = 0
btd n = n mod 10 + btd (n div 10)
sum' 0 = 0
sum' n = btd n + sum' (n-1)


and an explanation:

btd 0 = 0


stop case for btd.

btd n = n mod 10 + btd (n div 10)


takes the rightmost digit of n, and adds to it a call of itself using n without the rightmost digit (stops when n is 0; i.e. we divided n by ten and got 0, n has one digit).

sum' 0 = 0


stop case for sum'.

sum' n = btd n + sum' (n-1)


takes the sum of digits for n as defined above and adds to a call of itself using n-1 (stops when n = 0 as defined above)

– cat
Commented Jun 30, 2016 at 23:30

# Factor, 44

[ iota [ 1 + 10 >base ] map ""join >array [ 48 - ] [ + ] map-reduce ]


## Silicon, 9 bytes

0I\«S»îTM


Ugh, this is overly complicated in my opinion.

Anyways, explanation:

0I\«S»îTM

\          Push a list with integers in the range...
0            ...0 to...
I           ...the input.
«         Map
S        Split
»
î      Flatten list
T     Convert all list items to integers
M    Sum of list items
Implicit output


C#, 75 bytes

Console.Write(i.Select(j =>j.ToString().ToCharArray().Sum(k=>k-48)).Sum());


where i is the integer input sequence. Also, limited to integers.

## JavaScript (using external library) (48 bytes + 300 (penalty for library) = 348)

n=>_.Range(1,n).Sum(x=>_.From(x+"").Sum(y=>y|0))


Link to lib: https://github.com/mvegh1/Enumerable/

Code explanation: Library creates a range starting at 1 for n elements, and sums up a complex predicate applied for each integer in the range. The predicate converts the integer to a string, and _.From converts that to a char array internally, and then those digits are summed as integers.

# Java, 145 bytes

class X{public static void main(String[]a){long n=Long.parseLong(a[0]),s=0,i,z;for(i=1;i<=n;i++)for(z=i;z>0;z/=10)s+=z%10;System.out.print(s);}}


Tried to do with bonuses, but it turns out it wasn't worth it.

# C, 70 bytes

i,s;t(n){for(i=n;i;)for(n=i--;n;n=(n-n%10)/10)s+=n%10;printf("%d",s);}


# ? - 100 = - 61

set n [expr [string map ^\ ** $n]] time {incr s [expr [join [split$n ""] +]]
incr n -1} $n puts$s


Not sure if the -100 is deserved.

# Add++, 14 bytes

D,f,@,RbUBDBFs


Try it online!

### Octave 82 - (50 + 10) = 22 bytes

i=[1:eval(input())]
a=t=0
do
a=sum(mod(i,10))
t+=a
i=floor(i/10)
until a==0


# Japt, 5 bytes

A nice, simple golf before I log off for the weekend.

Although this qualifies for the -25 bonus (it can handle up to JS's max of 2**53-1), I haven't factored that into the byte count above 'cause bonuses are bad!

õì xx


Try it

The following 9 byte solution would also quality for the -50 and -10 bonuses, using ** for exponentiation.

OvU õì xx


Try it

## Explanation

          :Implicit input of integer U
õ         :Range [1,U]
ì        :Convert each to an array of digits
x     :Reduce each digit array by addition
x      :Reduce the main array by addition


DC(62)

There's definitely a more efficient answer with DC, but I'm inexperienced with both DC and code golf in general. (This is my first attempt, actually)

si[lidZ1<clt+stli1-sili0>qlbx]sb[dA%lt+stA/dZ1<c]sc[q]sqlbxltp


The input is the number to sum digits to already on the stack. For example, 20 would sum 1-20.

• The sequence of numbers should be generated by your code, not expected to find them all in the stack. Commented Jul 10, 2018 at 15:38
• Uhm… The problem is not related to site rules but the challenge: your code should take one integer, expand it the all numbers between 1 and the input then sum up their digits. Your code simply skips half of task. Commented Jul 10, 2018 at 16:16
• @manatwork ...I'm an idiot, completely missed half the problem. Thanks! Commented Jul 10, 2018 at 16:40