38
\$\begingroup\$

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.
\$\endgroup\$
  • 2
    \$\begingroup\$ And what should 55*96-12 return? \$\endgroup\$ – ProgramFOX Jan 15 '14 at 18:04
  • 1
    \$\begingroup\$ 55*96-12=5268, should be the same output as entered 5268 \$\endgroup\$ – ST3 Jan 15 '14 at 19:07
  • 3
    \$\begingroup\$ Bonuses may be a bit on the big side, seems to be becoming a competition on the biggest negative score :) \$\endgroup\$ – Joachim Isaksson Jan 15 '14 at 19:12
  • 7
    \$\begingroup\$ @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. \$\endgroup\$ – Cruncher Jan 15 '14 at 19:17
  • 3
    \$\begingroup\$ -1 because this challenge uses the outdated (and awful) scoring incentive of "bonuses". \$\endgroup\$ – mbomb007 May 9 '18 at 21:23

86 Answers 86

0
\$\begingroup\$

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;
\$\endgroup\$
0
\$\begingroup\$

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
   readln(a);
   for i := 1 to a do
      sum := sum + cs(i);
   writeln(sum);
end.
\$\endgroup\$
0
\$\begingroup\$

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
$ 
\$\endgroup\$
0
\$\begingroup\$

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)        
        }
    }
\$\endgroup\$
0
\$\begingroup\$

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)\\
% 
\$\endgroup\$
  • \$\begingroup\$ Well if it uses % then you do not get 50 bonus, however you can slightly increase code size and get bonus. \$\endgroup\$ – ST3 Jan 23 '14 at 9:03
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

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

\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – DJMcMayhem Jun 13 '16 at 16:10
  • \$\begingroup\$ @DrGreenEggsandIronMan thanks for the tip! Sorry I didn't realise you should include the spaces \$\endgroup\$ – george Jun 13 '16 at 16:54
0
\$\begingroup\$

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(e`f(5)`)
console.log(e`f(12)`)
console.log(e`f(10)`)
console.log(e`f(1000000)`)
console.log(e`f('55*96-12')`)

\$\endgroup\$
0
\$\begingroup\$

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)

\$\endgroup\$
  • \$\begingroup\$ Haskell not Haskel :) \$\endgroup\$ – cat Jun 30 '16 at 23:30
0
\$\begingroup\$

Factor, 44

[ iota [ 1 + 10 >base ] map ""join >array [ 48 - ] [ + ] map-reduce ]
\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

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.

enter image description here

\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

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);}
\$\endgroup\$
0
\$\begingroup\$

tcl, 99

- 50 - 10

? - 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

\$\endgroup\$
0
\$\begingroup\$

Add++, 14 bytes

D,f,@,RbUBDBFs

Try it online!

\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ The sequence of numbers should be generated by your code, not expected to find them all in the stack. \$\endgroup\$ – manatwork Jul 10 '18 at 15:38
  • \$\begingroup\$ 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. \$\endgroup\$ – manatwork Jul 10 '18 at 16:16
  • \$\begingroup\$ @manatwork ...I'm an idiot, completely missed half the problem. Thanks! \$\endgroup\$ – FlexEast Jul 10 '18 at 16:40
0
\$\begingroup\$

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.
\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
  • \$\begingroup\$ Output is incorrect for n > 10, you need to split numbers into digits, and sum them. \$\endgroup\$ – u_ndefined Oct 12 '18 at 12:50
0
\$\begingroup\$

Kotlin, 38 bytes

No bonuses. (Int) -> Int lambda.

{(1..it).sumBy{(""+it).sumBy{it-'0'}}}

Try it online!

\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
-1
\$\begingroup\$

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
\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – Iszi Jan 16 '14 at 7:13
  • \$\begingroup\$ 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 \$\endgroup\$ – Iszi Jan 16 '14 at 8:00
  • \$\begingroup\$ 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. \$\endgroup\$ – Iszi Jan 16 '14 at 8:58
  • \$\begingroup\$ 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? \$\endgroup\$ – microbian Jan 16 '14 at 15:32
  • \$\begingroup\$ 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. \$\endgroup\$ – Iszi Jan 16 '14 at 15:39
-1
\$\begingroup\$

Python, 20 chars

f=lambda n:n*(n+1)/2
\$\endgroup\$
  • 2
    \$\begingroup\$ 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. \$\endgroup\$ – Konrad Borowski Jan 16 '14 at 12:37
  • \$\begingroup\$ @xfix oh thanks for your comment, I will check my reading skills! \$\endgroup\$ – flonk Jan 16 '14 at 13:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.