# 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? – ProgramFOX Jan 15 '14 at 18:04
• Bonuses may be a bit on the big side, seems to be becoming a competition on the biggest negative score :) – Joachim Isaksson Jan 15 '14 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. – Cruncher Jan 15 '14 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. – Konrad Borowski Jan 16 '14 at 12:35
• -1 because this challenge uses the outdated (and awful) scoring incentive of "bonuses". – mbomb007 May 9 '18 at 21:23

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 Jan 23 '14 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. – James Jun 13 '16 at 16:10
• @DrGreenEggsandIronMan thanks for the tip! Sorry I didn't realise you should include the spaces – george Jun 13 '16 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)

• Haskell not Haskel :) – cat Jun 30 '16 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))


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.

# demo

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. – manatwork Jul 10 '18 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. – manatwork Jul 10 '18 at 16:16
• @manatwork ...I'm an idiot, completely missed half the problem. Thanks! – FlexEast Jul 10 '18 at 16:40

# Powershell, -4 = (46 bytes - 50 bonus)

param($n)"$(1..($n|iex))"-split''-join'+0'|iex  Test script (plus 2 extra variants with 47 bytes): $f = {
param($n)"$(1..($n|iex))"-split''-join'+0'|iex #param($n)"$(1..($n|iex))"-split''|%{$s+=+$_};$s #param($n)"$(1..($n|iex))"-replace'\d','+$0'|iex } @( ,(12,51) ,("3+9",51) ,("15-3",51) ,("4*3",51) ,("24/2",51) ,(5,15) ,(10,46) ) | % {$n,$e =$_
$r = &$f $n "$($e-eq$r): $r" }  Output: True: 51 True: 51 True: 51 True: 51 True: 51 True: 15 True: 46  Explanation: • param($n) is argument integer
• ($n|iex) evaluates or runs a specified string as a command and returns the results of the expression or command • "$(1..($n|iex))" generates a string like " 1 2 3 4 5 6 7 8 9 10 11 12..." • -split'' splits the string to array by chars and $null. Result like [$null,' ',$null,'1',$null,' ',$null,'2'...]
• -join'+0 joins all elements with delimiter '+0' to a string. Result like +01+0 +02+0 +03+0 +04+0 +05+0 +06+0 +07+0 +08+0 +09+0 +01+00+0 +01+01+0 +01+02+0...
• |iex alias for Invoke-Expression that evaluates or runs a specified string as a command and returns the results of the expression or command.

# Pepe, 39 bytes

REeErEEREEEEEEeREEEEereerRrEEEEEEEEreEE


Try it online! The link contains the word REE, woah.

## Explanation

REeE         # Take input to [R]
rEE          # Label [r] (implicit push 0)
REEEEEEe     # Copy the number to the other stack
REEEEe       # Decrement it
ree          # If reached [r] (0)
rRrEEEEEEEE  # Sum stack contents
reEE         # Print result

• Output is incorrect for n > 10, you need to split numbers into digits, and sum them. – u-ndefined Oct 12 '18 at 12:50

# 05AB1E, score: -49 (11 bytes -50-10 bonuses)

'^„**:.ELSO


Inefficient, but it works.

Try it online.

Explanation:

'^„**:        '# Replace every "^" with "**" of the (implicit) input
#  i.e. "55*96-2^6+156/3" → "55*96-2**6+156/3"
.E       # Eval the expression as a Python eval, resulting in a float n
#  i.e. "55*96-2**6+156/3" → 5268.0
L      # Create a list in the range [1, n]
#  i.e. 5268.0 → [1,2,3,....,5266,5267,5268]
S     # Convert each number to digits
#  i.e. [1,2,3,....,5266,5267,5268]
#   → ['1','2','3',...,'5','2','6','6','5','2','6','7','5','2','6','8']
O    # Take the total sum (and output implicitly)
#  i.e. ['1','2','3',...,'5','2','6','6','5','2','6','7','5','2','6','8']
#   → 81393


Would be 3 bytes without any bonuses:

LSO


Try it online.

# Kotlin, 38 36 bytes

{(1..it).sumBy{"$it".sumBy{it-'0'}}}  Try it online! PowerShell (146 - 50 = 96) This is a complete program. Save it as 'test.ps1' and run it from command line as PS > .\test.ps1  The code is: $v = read-host
$n = invoke-expression$v

[double] $s = 0 while ($n -gt 0) {
foreach($c in$n.tostring().tochararray()) {
$s += [int]$c - 48
}
$n-- }$s

• I'm pretty sure this can be trimmed a lot more. Also, if I'm not mistaken, it can't properly handle inputs greater than 2^63-1 because PowerShell defaults its integer types to signed. – Iszi Jan 16 '14 at 7:13
• Here's an optimization with a base score (no bonuses/penalties evaluated) of 90. NOTE: This is only a golfing of your existing code - any bugs or limitations inherent in this answer will still be present here. for($n=read-host|iex;$n-gt0;$n--){$n.tostring().tochararray()|%{[double]$s+=[int]$_-48}}$s – Iszi Jan 16 '14 at 8:00 • Correction: The script can probably deal with inputs of any size just fine. It will run into issues with any values for$s which are larger than (2^63)-1 though. And there's still a good load of optimization to be done even on the script I gave in the above comment. So much so that I just posted a separate answer which undercuts your original score by nearly 80 points. I strongly recommend you read the "Tips for golfing" threads around here, and check out other PowerShell answers, before trying to compete in the future. – Iszi Jan 16 '14 at 8:58
• I know I could do optimizations. And your answer is excellent. Generally I don't answer to compete/win, that's why I don't try to golf too much. Anyways, why a downvote? – microbian Jan 16 '14 at 15:32
• The down-vote isn't so much for being unnecessarily long (though that was a fair part of it - code-golf answers are generally expected to show at least some effort put into reducing the code size) as it is for not meeting the spec. By forcing \$s to a double, your script will be incapable of properly handling any numbers which sum up larger than (2^63)-1. Since the challenge requires that you be able to process inputs up to (2^64)-1, that renders this answer invalid. – Iszi Jan 16 '14 at 15:39

## Python, 20 chars

f=lambda n:n*(n+1)/2

• Check your reading skills. First of all, this cannot be a function. Second, this is just wrong, as it sums numbers (which is something completely different). Read the description before putting a solution. – Konrad Borowski Jan 16 '14 at 12:37
• @xfix oh thanks for your comment, I will check my reading skills! – flonk Jan 16 '14 at 13:22