45
\$\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\$
28
  • 2
    \$\begingroup\$ And what should 55*96-12 return? \$\endgroup\$
    – ProgramFOX
    Commented Jan 15, 2014 at 18:04
  • 4
    \$\begingroup\$ Bonuses may be a bit on the big side, seems to be becoming a competition on the biggest negative score :) \$\endgroup\$ Commented Jan 15, 2014 at 19:12
  • 9
    \$\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
    Commented Jan 15, 2014 at 19:17
  • 3
    \$\begingroup\$ @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. \$\endgroup\$
    – null
    Commented Jan 16, 2014 at 12:35
  • 3
    \$\begingroup\$ -1 because this challenge uses the outdated (and awful) scoring incentive of "bonuses". \$\endgroup\$
    – mbomb007
    Commented May 9, 2018 at 21:23

96 Answers 96

14
\$\begingroup\$

Mathematica 30-(10+50)= -30

Shortened by 4 chars thanks to ybeltukov.

Range@n returns the numbers from 1 through n.

Integerdigits@n breaks up each of those numbers into its digits.

Total[n,2] sums the digits. The 2 is to allow summing across different levels, i.e. lists of lists.

IntegerDigits@Range@#~Total~2&

Testing

IntegerDigits@Range@#~Total~2&[12]

51

IntegerDigits@Range@#~Total~2 &[1000000]

27000001


Expressions

IntegerDigits@Range@#~Total~2 &[55*96 - 12]

55*96 - 12

81393
5268

IntegerDigits@Range@#~Total~2 &[5268]

81393


IntegerDigits@Range@#~Total~2 &[55*96^2 - 12]
55*96^2 - 12

12396621
506868

IntegerDigits@Range@#~Total~2 &[506868]

12396621

\$\endgroup\$
11
  • \$\begingroup\$ You should add info on the valid arguments to get all brownie points :D \$\endgroup\$
    – Yves Klett
    Commented Jan 15, 2014 at 18:48
  • 1
    \$\begingroup\$ I don't know if I would consider that not using eval \$\endgroup\$
    – Cruncher
    Commented Jan 15, 2014 at 19:19
  • 3
    \$\begingroup\$ re: Eval in Mathematica. It's a symbolic language in which the front-end always tries to solve Math like that automatically. You'd have to add additional code (Hold[]) to prevent it from doing so. \$\endgroup\$ Commented Jan 15, 2014 at 20:46
  • 1
    \$\begingroup\$ Tr@Flatten can be reduced to Total[...,2]: IntegerDigits@Range@#~Total~2&. \$\endgroup\$
    – ybeltukov
    Commented Jan 15, 2014 at 23:40
  • 2
    \$\begingroup\$ Don't you handle arbitrarily large int and deserve another -25? \$\endgroup\$
    – aka.nice
    Commented Jan 16, 2014 at 0:33
12
\$\begingroup\$

C: 150 138 - (100+50) = -12

a,b,c;main(d){for(scanf("%d ",&a);~scanf("%c%d ",&d,&b);a=d^43?d%5?d%2?a/b:a*b:a-b:a+b);for(;a;)for(b=a--;b;b/=10)c+=b%10;printf("%d",c);}

Very shamefully stealing @Fors answer from here to do the expression evaluation: https://codegolf.stackexchange.com/a/11423/13877

Sample usage:

./a.exe <<< "5 + 7"
51

Note: the expression implementation assumes no operator precedence and consumes values as it receives them; ex, 1+2*3 = 9 rather than the typical 7.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ This doesn't deal with operator precedence, but the question doesn't specify whether standard operator precedence should apply... ping @ST3, this should probably be clarified. Anyway, it should probably be mentioned in the answer. \$\endgroup\$
    – FireFly
    Commented Jan 15, 2014 at 23:13
  • \$\begingroup\$ @FireFly I modified the answer to reflect this fact. \$\endgroup\$
    – Josh
    Commented Jan 16, 2014 at 13:55
  • \$\begingroup\$ @Josh - please provide answer for 2^64 - 5 \$\endgroup\$
    – SergeyS
    Commented Jan 19, 2014 at 12:24
11
\$\begingroup\$

sed, 411 283 - 25 = 258

I can't be bothered to golf it more right now. :-) Not recommended for use with even remotely big integers, but technically it could deal with arbitrarily large integers (you'll likely run out of RAM pretty quickly though, since I (more-or-less have to) encode the number in unary).

s/$/x0123456789/
:l
/9$/H
:b
s/(.)(y*x\1)/y\2/
/(.)y*x\1/b b
s/(.)([xy].*)(.)\1/\3\2\3\1/
:c
s/y(.*(.))/\2\1/
/y/b c
/0$/b f
/^0*x.*9$/!b l
x
s/x[^\n]*\n//g
:d
s/(.)(.*x.*(.)\1)/z\3\2/
/[^z0]x/b d
s/0|x.*|\n//g
H;x
s/./0/g
s/$/x9876543210/
x
:e
x
b l
:f
x
s/.//
/./b e
x
s/^0+|x.*//g

Sample use

(Input lines indented for easier reading.)

  5
15
  12
51
  33
183
\$\endgroup\$
9
\$\begingroup\$

Perl 6: 108 - (25 + 50 + 100) + 0 = -67 points

Golfed solution (Final line based off of xfix's great solution):

$!=get;for '*',&[*],'/',&[/],'+',&[+],'-',&[-] ->$s,&f{$!~~s:g[(\d+)$s(\d+){}]=f |@()}
say [+] (1..$!)».comb

Un-golfed solution:

my $expression = get;
for '*', &[*],
    '/', &[/],
    '+', &[+],
    '-', &[-]
-> $sym, &infix {
    $expression ~~ s:g[(\d+) $sym (\d+) {}] = infix($0, $1)
}
say [+] (1..$expression)».comb

The evaluation step works by iterating over each symbol of *, /, +, -, finding when that lies between two integers, and substituting that using the function that symbol represents.

In more detail: it takes each symbol (e.g. +) and the infix function that it's supposed to represent (e.g. &[+] which is the shorthand for &infix:<+> and the same function Perl 6 calls when you execute 1 + 2) and does a global substitution (s:g[…] = …, which is like Perl 5 s/…/…/ge), which matches two integers separated by the symbol ((\d+) $sym (\d+)), and substitutes it with the output of the corresponding infix function called with those integers (infix($0, $1)).

Finally, this evaluated expression is feed into say [+] (1..$expression)».comb, which xfix explains very well in his solution.

Sorry to be so late to the party ☺

EDIT: Removed support for exponents; it was exactly 10 characters anyway and didn't do associativity correctly.

\$\endgroup\$
4
  • \$\begingroup\$ This is great. I like how you made a very simple parser - I tried, but I didn't manage to make something as short as this. Instead of my $g you may want to use something predeclared (I think that $! could work, but I haven't tested). \$\endgroup\$
    – null
    Commented Mar 12, 2014 at 8:05
  • \$\begingroup\$ @xfix, I'm not sure how that would help the golf. There is one way to really golf it, but it requires the not yet fully functional "infix:[$var]" syntax: my$g=get;for <* / + -> {$g~~s:g[(\d+)$^s(\d+){}]=infix:[$^s] |@()};say [+] (1..$g)».comb This would get the score down to 88 chars or -97 points \$\endgroup\$
    – Mouq
    Commented Mar 12, 2014 at 22:34
  • \$\begingroup\$ Ohh, the $! would help get rid of the 'my '! Thanks @xfix \$\endgroup\$
    – Mouq
    Commented Mar 16, 2014 at 17:43
  • \$\begingroup\$ This doesn't really do order of operations correctly, does it? For example 5*2/2*5 would evaluate to 1, not 25. \$\endgroup\$
    – Jo King
    Commented Mar 14, 2020 at 11:32
8
\$\begingroup\$

python, 55-(50+25+10) = -30

In-efficient yet shorter and also able to handle expressions.

EDIT: Thanks Wolframh and legoStormtroopr for the tricks :D

s,t=0,input()
while t:s+=sum(map(int,`t`));t-=1
print s

python, 149-(25+50+10) = 64

My first version

def d(n):
 if n/10==0:return n*(n+1)/2
 c,t=0,n
 while t/10:c,t=c+1,t/10
 p=10**c;m=n%p
 return d(m)+t*(m+1)+p*t*(t-1)/2+p*c*t*45/10
print d(input())

input:

1234567891234567891234564789087414984894900000000

output:

265889343871444899381999757086453238874482500000214
\$\endgroup\$
10
  • \$\begingroup\$ I get an overflow error when I try running your xrange solution on 1234567891234567891234564789087414984894900000000 \$\endgroup\$
    – Josh
    Commented Jan 15, 2014 at 18:38
  • 1
    \$\begingroup\$ @Josh got rid of xrange :D \$\endgroup\$
    – Wasi
    Commented Jan 15, 2014 at 18:58
  • 2
    \$\begingroup\$ Some hints: You can replace eval(raw_input()) by input(). The while loop could be while t:s+=sum(map(int,t));t-=1. \$\endgroup\$ Commented Jan 15, 2014 at 22:44
  • 2
    \$\begingroup\$ You can shorten this by just using input() instead of eval(raw_input()), as input already evals the expression! This means you can get the -10 binus for the power symbol and the -100 bonus for not using eval!!! \$\endgroup\$
    – user8777
    Commented Jan 15, 2014 at 22:44
  • \$\begingroup\$ @LegoStormtroopr the rules say eval and similar, so I think the -100 wouldn't count \$\endgroup\$
    – SztupY
    Commented Jan 15, 2014 at 23:41
8
\$\begingroup\$

Python - 108 chars minus 85 bonuses, 23 strokes, handles very very very large inputs

Most of these solutions seem to be looping over all ints less than the input and adding up all their digit sums. This works, but I feel it's inelegant, and would question whether they're truly eligible for the 25 point bonus, since I don't think they'd be able to handle the input 1234567891234567891234564789087414984894900000000 within our lifetimes. Indeed, on an input of n digits, these solutions take O(10^n) time. I chose instead to throw some maths at this problem.

#Returns the sum of all digits in all x-digit numbers
def f(x):
    return x*(10**(x-1))*45

#Returns the sum of all numbers up to x
def g(x):
    return x*(x+1)/2
    
#Solves the problem quickly
def magic(x):
    digits = [int(y) for y in list(str(x))]
    digits.reverse()
    total = 0

    for (sig, val) in enumerate(digits):
        total += (10**sig)*g(val-1) + val*f(sig) + val + (val*10**sig)*sum(digits[sig+1:])
    return int(total)
    

The set of all x digit numbers is isomorphic to the set {0,1,2,3,4,5,6,7,8,9}^x. For a fixed (n,sig) there are x different values for sig, 10^x-1 points with the sigth index set to n, and the sum of all digits 0-9 is 45. This is all handled by f.

g is something we're probably all familiar with

magic takes all the digits in the input number, and iterates over them from least to most significant. It's easiest to track this with an example input, say 1,234,567.

To deal with the range 1,234,567-1,234,560, we must add up all digits from 1 to 7, and add on 7 times the sum of the other digits, to deal with all numbers greater than 1,234,560. We now need to deal with the remainder.

To deal with the range 1,234,560-1,234,500, we add on the 6 (val), and drop the upper limit to 1,234,559. In making the remainder of the drop, we'll see every single-digit number 6 times (val*f(sig)). We'll see all the numbers from 0 to 5 exactly 10 times each ((10**sig)*g(val-1)). We'll see all the other digits in this number exactly 60 times ((val*10**sig)*sum(digits[sig+1:])). We have now dealt with all numbers strictly greater than 1,234,500. The same logic will apply inductively across all significances.

Golfing this, with thanks to WolframH, reduces this solution to

d=map(int,str(input()))
print sum(v*(10**s*((v-1)/2+sum(d[:~s]))-~s*9*10**s/2)for s,v in enumerate(d[::-1]))

And the sum of the digit sums of all integers up to 1234567891234567891234564789087414984894900000000 is 265889343871444927857379407666265810009829069029376

The largest number I've managed to throw at the golfed version is 10^300, at which point the floats start overflowing and numeric instability starts to cause problems. With a quick square-and-multiply exponentiation function, this problem would vanish.

And LaTeX support would be really useful...

\$\endgroup\$
9
  • \$\begingroup\$ Nice. I tried to attack this problem with maths a while ago, but got stuck. I'll have to go over this carefully later and have to think about how it works. \$\endgroup\$
    – FireFly
    Commented Jan 16, 2014 at 13:47
  • \$\begingroup\$ Nice answer! It is similar into the way I counted, that would be if input is 1000000 :) \$\endgroup\$
    – ST3
    Commented Jan 16, 2014 at 19:35
  • 1
    \$\begingroup\$ +1 for using maths. However, I get 2.65889343871e+50, which is a floating point approximation of the real solution. Apparently you printed int(t) instead of t as in the code you gave. That is wrong; the real solution is 265889343871444899381999757086453238874482500000214. Just avoid using floats, i.e. replace **(x-1) by the shorter **x/10. \$\endgroup\$ Commented Jan 17, 2014 at 21:55
  • 1
    \$\begingroup\$ Golfing this a little bit more. It's clear that the only global needed is d (because it's used twice). Eliminating the others (and using some tricks) one arrives at d=map(int,str(input()))\nprint sum(v*(10**s*((v-1)/2+sum(d[:~s]))-~s*9*10**s/2)for s,v in enumerate(d[::-1])) (108 characters). Runs fine on inputs of any size (like int("1"*1000)). \$\endgroup\$ Commented Jan 17, 2014 at 22:23
  • 1
    \$\begingroup\$ @ymbritt 10**-1 is 0.1, and from there on everything gets turned into floats. 1/10 is 0 (integer division), and everything can stay ints. \$\endgroup\$ Commented Jan 18, 2014 at 20:39
8
\$\begingroup\$

TI-BASIC, 137 - (50 + 10 + 100) = -23

Input A:Disp cumSum(randIntNoRep(1,A))→L₁:"?:For(A,1,dim(L₁:Ans+sub("ABCDEFGHIJKLMNOPQRSTUVWXYZ",L₁(A),1:End:Disp sub(Ans,2,length(Ans)-1

Input handles numbers up to 1E100 and automatically evaluates. Can handle expressions.

Although it is an insanely large array, I'm not wasting computer resources (this is run from a calculator).

\$\endgroup\$
9
  • 1
    \$\begingroup\$ best answer for this question I think. using a calculator language to write a code golf answer for adding numbers together. so cool! \$\endgroup\$
    – Malachi
    Commented Jan 15, 2014 at 22:29
  • 1
    \$\begingroup\$ @Malachi As I always say, when code golf = math, it's time to pull out the calculator. \$\endgroup\$
    – Timtech
    Commented Jan 15, 2014 at 22:29
  • 2
    \$\begingroup\$ My version that allowed numbers up to 9E99 wasn't good enough apparently, so I don't think you can count that bonus. Also, I'm pretty sure you'll have to count the input as "with eval", per Carraher's Mathematica answer. \$\endgroup\$
    – FireFly
    Commented Jan 15, 2014 at 23:02
  • 1
    \$\begingroup\$ Agree with FireFly, bonus of not using eval shouldn't be taken. \$\endgroup\$
    – ST3
    Commented Jan 16, 2014 at 7:17
  • 3
    \$\begingroup\$ How is a calculator not a computer? \$\endgroup\$ Commented Jan 16, 2014 at 18:25
6
\$\begingroup\$

Scala 66

println((1 to readLine().toInt).flatMap(x=>(x+"").map(_-'0')).sum)
\$\endgroup\$
6
\$\begingroup\$

C, 77 74

n,v,i;main(){scanf("%d",&n);for(;i||(i=n--);i/=10)v+=i%10;printf("%d",v);}

C, 150 124 - 25 = 99

Here is an alternative version that should technically be eligible for the 25 bonus for "any" positive integer, but it's impractically slow since the algorithm is linear-time in its input. Regardless, it was fun to write. Manually subtracts a number read in as ASCII characters. This version is 150 characters. (Now with horrible, argument-thrashing, loopful code!)

n,v;main(int n,char**a){char*p;do{for(p=a[1];*p>47;p++)v+=*p-48;for(;*--p==48;)*p=57;
p[0]--;}while(p>=a[1]);printf("%d",v);}

C, 229 224 - (50 + 100) = 74

Expression-handling variation. Implements operator precedence according to typical rules: / * - +. Limited to 97 tokens = 48 terms.

#define F(X,Y)for(q=n+1;q+1!=p;)*q-X?q+=2:(q[-1]Y##=q[1],memmove(q,q+2,(p-q)*4))
n[99],*p,*q,v,i;main(){for(p=n;~scanf("%d%c",p,p+1);)p+=2;F('/',/);F('*',*);
F('-',-);F('+',+);for(;i||(i=n[0]--);i/=10)v+=i%10;printf("%d",v);}
\$\endgroup\$
2
  • \$\begingroup\$ All positive integers mean, that it should handle even longer then 99 digits numbers. \$\endgroup\$
    – ST3
    Commented Jan 15, 2014 at 20:34
  • \$\begingroup\$ @Firefly cool algorithm to work on numbers larger than the builtin numerics! \$\endgroup\$
    – Josh
    Commented Jan 15, 2014 at 20:40
6
\$\begingroup\$

Husk, 4 bytes

Σṁdḣ

Try it online!

  • makes a range from 1 to input
  • ṁd flatmap digits
  • Σ sum
\$\endgroup\$
1
  • 2
    \$\begingroup\$ Welcome to Code Golf, and nice answer! \$\endgroup\$
    – rydwolf
    Commented Nov 21, 2021 at 2:32
5
\$\begingroup\$

GolfScript 18 - 50 = -32

~),{`+}*' '*~]{+}*

Explanation: Suppose input is "12":

~), # turn input into integer, increment, and then turn into an array of all numbers less than or equal to input.  

Stack is [0,1,2,3,...,12].

{`+}* # fold string concatenation across the array

Stack is "01234...9101112".

' '* # join a space between all characters

Stack is "0 1 2 ... 1 0 1 1 1 2".

~] # evaluate the stack into an array.  No `[` is necessary since the stack is otherwise empty.

Stack is [0,1,2,...,9,1,0,1,1,1,2].

{+}* # fold addition across the new array

Stack is 51, as desired.

The input here could be any valid GolfScript expression, which can include exponents. For example:

echo "5 5 + 2 * 8 -" | ruby golfscript.rb h.gs
-> 51

Since 2(5 + 5) - 8 = 12. I think this should qualify for the bonus, but maybe it was expected to be only if in normal form, not the reverse Polish notation of GolfScript.

\$\endgroup\$
4
  • \$\begingroup\$ Does it support ^ as well? \$\endgroup\$
    – SztupY
    Commented Jan 16, 2014 at 9:55
  • \$\begingroup\$ It supports exponentiation in GolfScript syntax, which is ? \$\endgroup\$
    – Ben Reich
    Commented Jan 16, 2014 at 14:45
  • \$\begingroup\$ You do not get bonus 10, because program must support ^, not ? or pow and etc. \$\endgroup\$
    – ST3
    Commented Jan 16, 2014 at 19:31
  • \$\begingroup\$ @ST3 As you wish! \$\endgroup\$
    – Ben Reich
    Commented Jan 16, 2014 at 19:43
4
\$\begingroup\$

Ruby, 37 - 50 = -13

Double eval, all the way across the sky! As with the other Ruby solutions, I think this should theoretically be able to work with arbitrarily large numbers, but execution time would be... dire.

p eval [*1..eval(gets)].join.chars*?+

Older version (49 - 50 score)

p"#{[*1..eval(gets)]}".chars.map(&:to_i).inject:+

Assuming the 10 character bonus actually requires the character for exponentiation to be a caret, the shortest way I could think to add that is:

.gsub ?^,'**'

Which costs more characters than the bonus would give.

\$\endgroup\$
2
  • \$\begingroup\$ You can remove a few chars: p"#{[*1..eval(gets)]}".chars.map(&:to_i).inject :+ \$\endgroup\$
    – SztupY
    Commented Jan 15, 2014 at 23:47
  • \$\begingroup\$ @SztupY good call, thanks! I don't use & nearly enough in golf. In fact, you don't need the space between inject and :+ either. \$\endgroup\$ Commented Jan 15, 2014 at 23:54
4
\$\begingroup\$

Perl 6 (28 - 75 + 0 = -47 bytes)

say [+] (1..get.eval)».comb

It can handle all positive numbers (however, big ones will take a long while, because currently Perl 6 implementations are slow, but Perl 6 supports big integers natively). It uses eval, in order to implement a simple calculator (five character penalty for fifty characters is worth it). It's slow just because current implementations are slow, but in theory, it should be fast enough (when Perl 6 implementations improve, that is). Also, surprisingly, I win with the Mathematica (for now).

» in this code is actually not needed, but I put it here for performance reasons (otherwise, program would allocate entire string. The reason why it's here is that Perl 6 doesn't have infinite strings, but it does have infinite lists.

Anyway, you may ask how this code even works. Well, I'm going to pass it part by part.

  • get.eval

    This gets one line (get function), and evaluates it (eval method).

  • 1..get.eval

    After that, Perl 6 prepares a range object, from 1 to evaluated value. This is a range, so nothing huge is allocated.

  • ».comb

    .comb method splits string onto characters (unless called with an argument). For example, 'cat'.comb returns 'c', 'a', 't'. » maps the list elements, so .comb is ran on its every item - not only on the list itself (for example, (4, 9)».sqrt gives 2, 3). This also doesn't allocate more than needed, because Perl 6 has infinite lists (like Haskell, for example).

    » character actually not needed, as .comb can be used directly on the list, but this involves implicit string coercion (and Perl 6 doesn't have infinite strings, so this would waste memory). For example, 1, 2, 3 list after conversion to the string returns 1 2 3. For Perl 6, a space is a perfectly fine number meaning 0, so the code would work, even with such conversion. However, it would abuse computing resources.

  • [+]

    This is a reduce operator. Basically, between [], you can put an operator to use, in this case +. The list after reduce operator is reduced, so [+] 1, 2, 3 is 1 + 2 + 3, which is 6. Perl 6 uses separate operators for numbers and strings, so it won't be considered to be concatenation.

  • say

    Finally, say outputs the result. After all, you want to see the final result, don't you?

\$\endgroup\$
4
  • \$\begingroup\$ Hmmm... [+] 1,2,3,4,5,6,7,8,9,10 is 1+2+3+4+5+6+7+8+9+10, am I right? \$\endgroup\$
    – ST3
    Commented Feb 11, 2014 at 11:14
  • \$\begingroup\$ @ST3: Yes. Reduce operator can be used in many interesting ways in Perl 6. For example, > can be chained, so 3 > 2 > 1 is true. The same property applies to reduce operators, so [>] 3, 2, 1 is still true, as it means 3 > 2 > 1 - [>] can be used to determine if numbers are in descending order. \$\endgroup\$
    – null
    Commented Feb 11, 2014 at 18:55
  • \$\begingroup\$ couldn't you use get.Int instead of eval ? Does it need math expressions ? \$\endgroup\$
    – Ven
    Commented Apr 18, 2014 at 8:57
  • \$\begingroup\$ @user1737909: "-50 Bonus if your code can handle simple expressions". Also, Perl 6 doesn't need casting by design (aside of few rare edge cases, like sort without comparison method argument). \$\endgroup\$
    – null
    Commented Apr 18, 2014 at 12:34
4
\$\begingroup\$

Perl 31 - No bonuses

map{s/./$%+=$&/ge}0..<>;print$%

Sample output:

perl -e 'map{s/./$%+=$&/ge}0..<>;print$%'
1000000
27000001

Perl 5 with -p, 50 - 28 bytes: -22

map$\+=$_,/./g for 1..eval}{

Try it online!

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

J, 22

([:+/[:"."0[:":>:@:i.)

Explanation

Evaluation proceeds from right to left.

i. n -> 0 1 2...n-1

>: n -> n+1

": numbers -> 'numbers'

"."0 -> (on each scalar item) apply ". -> '123' -> 1 2 3

+/ -> sum
\$\endgroup\$
6
  • \$\begingroup\$ Downvoter needs to explain their objections to this answer. I've just tried it and, while it doesn't earn any bonuses, it works just fine as far as I can see. \$\endgroup\$
    – Gareth
    Commented Jan 16, 2014 at 6:56
  • \$\begingroup\$ Actually, having looked at the top answer, this one also seems to earn the expressions and power operator bonuses for a score of 22-60 = -38. \$\endgroup\$
    – Gareth
    Commented Jan 16, 2014 at 7:00
  • \$\begingroup\$ This +/,10#.inv>:i. would be shorter. But it still a function and not a complete program as OP asked. \$\endgroup\$
    – swish
    Commented Jan 16, 2014 at 17:27
  • \$\begingroup\$ @Gareth Bonuses don't apply to this answer, because you would just write expressions inside code and not as input. \$\endgroup\$
    – swish
    Commented Jan 16, 2014 at 17:33
  • 1
    \$\begingroup\$ @swish That's what I thought at first, but the Mathematica answer seems to work much like this. \$\endgroup\$
    – Gareth
    Commented Jan 16, 2014 at 18:52
3
\$\begingroup\$

R, 64 - (50 + 10) = 4

sum(utf8ToInt(paste(0:eval(parse(t=scan(,""))),collapse=""))-48)

When this is run, the user is asked for input.


Old version (cannot handle expressions): 46 characters:

sum(utf8ToInt(paste(0:scan(),collapse=""))-48)
\$\endgroup\$
4
  • \$\begingroup\$ It occurs to me that codegolf is wildly biased towards languages with single-symbol functions. This solution would be considerably shorter if we predefined u<-function(x) utf8ToInt(x) and so on. \$\endgroup\$ Commented Jan 16, 2014 at 16:13
  • \$\begingroup\$ @CarlWitthoft This is true. But the predefinition also counts for the number of characters. By the way: It's sufficient to have u <- utf8ToInt without function. This can be helpful for code golf if the function is used multiple times. \$\endgroup\$ Commented Jan 16, 2014 at 16:28
  • \$\begingroup\$ so if I create a Rcheatcodegolf package, is it legal to use the predefined functions in that package? :-) \$\endgroup\$ Commented Jan 16, 2014 at 16:34
  • \$\begingroup\$ @CarlWitthoft Yes, packages can be used. Of course, the package should not be written for the task. But if it includes short names for functions only, it's ok. \$\endgroup\$ Commented Jan 16, 2014 at 16:52
3
\$\begingroup\$

Batch - (181 - 50) - 131

Just for a bit of fun.

@set/av=%1
@setLocal enableDelayedExpansion&for /L %%a in (1,1,%v%)do @set a=%%a&powershell "&{'%%a'.length-1}">f&set/pb=<f&for /L %%c in (0,1,!b!)do @set/as+=!a:~%%c,1!
@echo !s!

I'll make it a bit more readable:

@set /a v=%1
setLocal enableDelayedExpansion
for /L %%a in (1,1,%v%) do (
    @set a=%%a
    powershell "&{'%%a'.length-1}">f
    set /p b=<f
    for /L %%c in (0,1,!b!) do @set /a s+=!a:~%%c,1!
)
@echo !s!

Old method uses for loop to get output of powershell command, as opposed to writing to and reading from a file:

@set /a v=%1
@setLocal enableDelayedExpansion&for /L %%a in (1,1,%v%)do @set a=%%a&for /F usebackq %%b in (`powershell "&{'%%a'.length-1}"`)do @for /L %%c in (0,1,%%b)do @set /a s+=!a:~%%c,1!
@echo !s!

Set the input to a variable - v - using /a to accept arithmetic expressions.
Unfortunately enabling delayed expansion was necessary.
Use a for loop to count from 1 to the inputted value - v.
In order to handle numbers greater than 9, I had to use powershell to get the length of the string then use another for loop to split that string up, and add it to the sum - s.
You could change the name of powershell.exe to p.exe under C:\WINDOWS\System32\WindowsPowerShell\v1.0\ then call it with just p "&{'%%a'.length-1}, saving 9 bytes. But that's not really in the spirit of it.

H:\>sumof.bat 12
51
H:\>sumOf.bat (55*96-12)
81393

Left that second one running while I took my lunch break.

I can't really test it with numbers that are too much larger than this due to how slow it is. However it should work for fairly large numbers. 2147483647 is the largest number it will take (maximum 32 bit integer) before giving the following error -

H:\>sumOf.bat 2147483648
Invalid number.  Numbers are limited to 32-bits of precision.

This of course disqualifies me from the challenge.

\$\endgroup\$
7
  • 1
    \$\begingroup\$ Nice solution! There are a few ways to golf this down. 1. You can get rid of the temporary variable v and use %1 directly. 2. You can subtract 1 within your PowerShell script rather than the lengthy @set /a b=%%b-1 which saves you a bunch. With those changes, I have it down to 211 from the original 240. :-) \$\endgroup\$
    – Mark
    Commented Jan 16, 2014 at 19:00
  • \$\begingroup\$ Oops, I see now why you kept your temp variable (for the bonus points). The PowerShell tip still stands, though... \$\endgroup\$
    – Mark
    Commented Jan 16, 2014 at 20:06
  • \$\begingroup\$ Well spotted, Thanks. Will change that now. \$\endgroup\$
    – unclemeat
    Commented Jan 16, 2014 at 21:37
  • \$\begingroup\$ Batch won't work. It's limited to (2^31)-1 (signed 32-bit integer). The challenge requires handling of inputs up to (2^64)-1 (unsigned 64-bit integer, but the output for that value would overflow it). This is where PowerShell has a distinct advantage - its [decimal] type allows for values up to (2^96)-1. \$\endgroup\$
    – Iszi
    Commented Jan 16, 2014 at 22:52
  • 1
    \$\begingroup\$ I will give Batch some good credit for defaulting to integer division, though. That's something PowerShell is missing entirely. \$\endgroup\$
    – Iszi
    Commented Jan 16, 2014 at 22:59
3
\$\begingroup\$

Dyalog APL, 9 – 160* = -151

+/⍎¨∊⍕¨⍳⎕

Try it online!

get evaluated input
 e.g. "7+5" gives 12

indices 1 ... n
[1,2,3,4,5,6,7,8,9,10,12]

⍕¨ format each number into string
["1","2","3","4","5","6","7","8","9","10","11","12"]

enlist (flatten)
"123456789101112"

⍎¨ execute each character (yields list of single digit numbers numbers)
[1,2,3,4,5,6,7,8,9,1,0,1,1,1,2]

+/ sum  51


* Scoring

-50 bonus as it even accepts expressions as input. The expression must be valid APL, which is acceptable according to OP.

-10 bonus because because it also handles the ^ (* in APL).

-100 bonus because expression input is handled without explicit usage of eval (i.e. in APL).

\$\endgroup\$
5
  • \$\begingroup\$ Are you sure the -100 bonus is added here? Because it states "-100 Bonus if your code qualifies for the -50 bonus and does not use eval or similar to handle expressions." Since ⍎¨ seems to execute each character one by one, it's kinda the same as an eval (except it executes the characters one by one instead of all at the same time like eval does). \$\endgroup\$ Commented Oct 9, 2018 at 11:56
  • \$\begingroup\$ @KevinCruijssen Yes, as it does not use eval or similar to handle expressions. ⍎¨ is only used to convert digits to integers, not to handle expressions. \$\endgroup\$
    – Adám
    Commented Oct 9, 2018 at 12:00
  • \$\begingroup\$ Ah wait, I looked at your explanation incorrectly. But isn't the kinda an input+eval builtin then, or is eval always done implicitly when expressions are input? \$\endgroup\$ Commented Oct 9, 2018 at 12:06
  • 1
    \$\begingroup\$ @KevinCruijssen always takes an expression as input, evaluates it, and returns its result. So to input a string, you'd have to put quotes around it. The fact that a related built-in () returns the input as raw text shouldn't matter (especially since the symbols indicate that is the primary input method, and is a special variant), as otherwise getting the bonus would require implementing a math evaluator — an entirely different task than the main one. I don't like bonuses, and the -100 one is just silly or had APL in mind, but imho, it does seem an exact fit for the bonus. \$\endgroup\$
    – Adám
    Commented Oct 9, 2018 at 12:19
  • \$\begingroup\$ If is indeed the normal way of getting input and automatically handles expressions, I indeed see it fit into the bonus as well, so +1 from me. Bonuses are silly these days anyway, but nice way of utilizing them to minimize your score. \$\endgroup\$ Commented Oct 9, 2018 at 12:22
3
\$\begingroup\$

Vyxal, 3 - 160 = -157 bytes

ɾṅ∑

Try it Online!

Gaming. Use ** for pow. This works because all input is auto evaluated

\$\endgroup\$
2
\$\begingroup\$

C# (161)

using C=System.Console;using System.Linq;class X{static void Main(){C.WriteLine(Enumerable.Range(1,int.Parse(C.ReadLine())).SelectMany(i=>i+"").Sum(c=>c-48));}}

Pretty

using C = System.Console;
using System.Linq;

class X
{
    static void Main()
    {
        C.WriteLine(
            Enumerable.Range(1, int.Parse(C.ReadLine()))
                .SelectMany(i => i + "")
                .Sum(c => c - 48)
            );
    }
}
\$\endgroup\$
2
\$\begingroup\$

Python3+Bash (78 - 185 = -107)

python3 -c"print(sum(sum(map(int,str(x+1)))for x in range(int(${1//^/**}))))"
  • can handle all positive number
  • can handle expressions with + - / * operation
  • can handle ^ (power) operator.
  • can handle expressions, without eval or similar¹

If the result of expression is not integer, it will be truncated first. If the result of the expression is negative, the result is undefined.

Use it like:

bash golf.sh "12 + (42 / 3 + 3^4)"

1: unless you count invoking Python from Bash as such, but I don't think it is the case. If you think that it actually is, then the adjusted score is -7.

\$\endgroup\$
2
  • \$\begingroup\$ I would say that if you didn't write an expression evaluator, then you're using something equivalent to eval. But I'm not the OP, so good luck! \$\endgroup\$
    – Tobia
    Commented Jan 16, 2014 at 21:24
  • \$\begingroup\$ Agree with @Tobia, no bonus for expression evaluator. \$\endgroup\$
    – ST3
    Commented Feb 3, 2014 at 8:43
2
\$\begingroup\$

Java, 254

class T
{
    public static void main(String[] a)
    {
        long target = 10, count = 0;
        String[] digits = new String[50];
        for (long i = 1; i <= target; i++)
        {
            digits = String.valueOf(i).split("(?!^)");
            for (int j = 0; j < digits.length; j++)
                if (digits.length > j)
                    count += Integer.parseInt(digits[j]);
        }
        System.out.println(count);
    }
}

Handles expressions. Give whatever expression you desire in target. Handles until the length long can handle. If you clean up taking off all spaces into one line, and no statement to print, it counts to 254 chars (considering the long long words based Java programming).

PS: This is a complete program, not just logic. Words count given for the program, not just the logic.

\$\endgroup\$
2
\$\begingroup\$

Java (JDK8), 272

My first challenge I'm in, suggestions are welcome =)

import java.util.*;import java.util.stream.*;class C{public static void main(String[]a){System.out.print(Arrays.asList(IntStream.range(1,new Integer(a[0])).mapToObj(s->s+"").collect(Collectors.joining()).split("")).stream().map(Integer::valueOf).reduce(0,Integer::sum));}}

Indented:

import java.util.*;
import java.util.stream.*;

class C {

   public static void main(String[] a) {
     System.out.print(Arrays.asList(IntStream.range(1,new Integer(a[0]))
            .mapToObj(s->s+"")
            .collect(Collectors.joining())
            .split(""))
            .stream()
            .map(Integer::valueOf)
            .reduce(0,Integer::sum));
  }
}
\$\endgroup\$
1
  • \$\begingroup\$ +1 as everyone who does golf code challenge in java deserves it, but seems like Stream API does not give you advantage while you are golfing. Ill bet if you rewrite your solution and you will use loops instead streams it will be shorter. \$\endgroup\$
    – user902383
    Commented Jul 28, 2016 at 13:09
2
\$\begingroup\$

CJam, 9 - 25 = -16

CJam is a few months younger than this challenge, so this is not eligible for the green checkmark. Furthermore, this isn't beating Perl in the first place. ;) I quite liked the approach though, so I wanted to post it anyway.

l~),s:~:+

Test it here.

The idea is to create a range from 0 to N. This range is then converted to a string, which just concatenates the integers back to back. For N = 12, we'd get

"0123456789101112"

Then each character is converted to a integer with :~ (yielding an array of integers), and then summed up with :+. CJam can deal with arbitrarily big integers.

\$\endgroup\$
2
\$\begingroup\$

Python 3 + astor, 1017 1007 bytes - (25 + 50 + 100) = Score: 842 834

saved 10 bytes by removing ts and changing p

edit: I am unable to test the ridiculously long integer (1234567891234567891234564789087414984894900000000) [hangs my computer] but from my knowledge, Python 3 supports arbritrarily long integers.

This implementation uses abuses AST. I wouldn't consider abusing AST as "eval or similar".

from ast import*
from astor import*
nt,bo,m,d,a,s,n,p,ty=NodeTransformer,BinOp,Mult,Div,Add,Sub,Num,map,type
class M(nt):
    def visit_BinOp(t,z):
        if ty(z.left)==bo and ty(z.right)==bo:return bo(t.visit_BinOp(z.left),z.op,t.visit_BinOp(z.right))
        if ty(z.left)==bo:return bo(t.visit_BinOp(z.left),z.op,z.right)
        if ty(z.right)==bo:return bo(z.left,z.op,t.visit_BinOp(z.right))
        if ty(z.op)==m:return n(z.left.n*z.right.n)
        if ty(z.op)==d:return n(z.left.n/z.right.n);return z
class A(nt):
    def visit_BinOp(t,z):
        if ty(z.left)==bo and ty(z.right)==bo:return bo(t.visit_BinOp(z.left),z.op,t.visit_BinOp(z.right))
        if ty(z.left)==bo:return bo(t.visit_BinOp(z.left),z.op,z.right)
        if ty(z.right)==bo:return bo(z.left,z.op,t.visit_BinOp(z.right))
        if ty(z.op)==a:return n(z.left.n+z.right.n)
        if ty(z.op)==s:return n(z.left.n-z.right.n);return z
class S(nt):
    def visit_Num(t,z):return n(sum(p(int,list("".join(p(str,range(1,z.n+1)))))))
print(to_source(S().visit(A().visit(M().visit(parse(input()))))))

Too lazy to write ungolfed, so I'll give you an explanation of the classes:

M(NodeTransformer|nt) - converts multiplication and division into their results.
A(NodeTransformer|nt) - converts addition and subtraction into their results.
S(NodeTransformer|nt) - converts numbers into their sum of digits via the Pythonic (naïve) way.

The last line just executes these classes in the appropriate order on the input, to preserve order of operations, and prevent unwanted behavior.

Example usage ($ or > means user input) and by the way, the actual program takes input only once:

$ python3 summer.py
> 5
15
> 10
46
> 12
51
> 1000000
27000001
> 55*96-12
81393
\$\endgroup\$
5
  • \$\begingroup\$ This is amazing, but yet horrifying. Not sure if it's allowed (to knowingly use a long solution), but 10/10 from me. \$\endgroup\$
    – Riker
    Commented Jun 23, 2016 at 22:35
  • \$\begingroup\$ @EᴀsᴛᴇʀʟʏIʀᴋ Why isn't it allowed to knowingly use a long solution? I see no problem. At least I'll beat solutions with 842+ score ;) \$\endgroup\$
    – user36215
    Commented Jun 23, 2016 at 23:15
  • \$\begingroup\$ They are supposed to be competetive answers, meaning show effort. Also, DELETE THAT COMMENT. SE LIMIT FOR AGE IS 13!!! You should probably wait until you are legally allowed to be on. Due to COPPA (google it), you need to be 13 to use the internet like this. \$\endgroup\$
    – Riker
    Commented Jun 24, 2016 at 2:18
  • \$\begingroup\$ @EᴀsᴛᴇʀʟʏIʀᴋ Now I'm curious, who was that user? \$\endgroup\$
    – cat
    Commented Jun 30, 2016 at 23:29
  • 1
    \$\begingroup\$ @cat An arabic name I couldn't pronounce? Probably nuked account. \$\endgroup\$
    – Riker
    Commented Jul 2, 2016 at 12:28
2
\$\begingroup\$

Jelly, 5 - 160 = -155 bytes

ƓRDFS

Try it online!

Ɠet evaluated input, turn it into a Range, get the Digits of each, Flatten into a single list, then Sum

Claims the same bonuses as the APL answer. Exponents must be with ** instead of ^

\$\endgroup\$
5
  • 1
    \$\begingroup\$ I think adding Ɠ to the beginning is just a free -160. \$\endgroup\$
    – Razetime
    Commented Apr 6, 2021 at 16:45
  • \$\begingroup\$ @Razetime How would it count for the -100 and the -10? Unless I'm missing something, it would be leaning on Jelly evaling the input, which also wouldn't handle ^ (Python uses ** instead) \$\endgroup\$ Commented Apr 6, 2021 at 16:49
  • 1
    \$\begingroup\$ @Razetime -150 possibly, depending on the question's definition of "eval". Given that there's a "non-eval input" atom as well, I think that only claims the -50 \$\endgroup\$ Commented Apr 6, 2021 at 16:50
  • 1
    \$\begingroup\$ The APL answer seems to do the same thing and claim -160. \$\endgroup\$
    – Razetime
    Commented Apr 6, 2021 at 16:51
  • 1
    \$\begingroup\$ If there's precedence of an answer doing it, I think that's ok (especially on such a poorly worded challenge) (cc @UnrelatedString) \$\endgroup\$ Commented Apr 6, 2021 at 16:52
2
\$\begingroup\$

Pyth, 6 bytes

ssMjkS

Try it online!

  • S create range from 1 to input
  • jk join on k (initially empty string)
  • sM map to number
  • s sum
\$\endgroup\$
2
\$\begingroup\$

Regex 🐇 (Perl / PCRE2), 32 bytes, score 7

(\4?+(?=(x*)(\2{9})(x*))\3)+\2x+

Takes its input in unary, as a string of x characters whose length represents the number. Returns its output as the number of ways the regex can match. (The rabbit emoji indicates this output method. It can yield outputs bigger than the input, and is really good at multiplying.)

The -25 bonus applies because there is no inherent limit to the numbers a unary regex can take as input – though in standard regex engines an amount of memory must be allocated in bytes equal to the number being input. This doesn't apply to RegexMathEngine, which has a numeric mode, but I haven't yet implemented this output method in it.

Try it online! - Perl v5.28.2 / Attempt This Online! - Perl v5.36+
Try it online! - PCRE2 v10.33 / Attempt This Online! - PCRE2 v10.40+

Although Perl and PCRE2 (and Raku, though its syntax is different) are the only regex engines currently capable of counting the number of possible matches without their source code being patched, this regex itself only uses an ECMAScript level of functionality.

                 # No anchor. This will result in the regex being able to match
                 # starting at any position, ranging from the input number to 0,
                 # meaning tail will equal each of those values in turn. Each will
                 # count towards the total number of possible matches.
(
    \4?+         # If this is the first iteration, do nothing, because \4 is unset.
                 # Otherwise, tail -= \4.
    (?=          # Atomic lookahead. Match what is inside, but upon exiting it,
                 # jump back to the position we were at before entering it, and
                 # never backtrack back into the lookahead to try different
                 # matches.
        # \2 = floor(tail / 10); \3 = \2 * 9; \4 = tail % 10
        (x*)(\2{9})(x*)
    )
    \3           # tail = tail - \3 == \2 + \4; leave \4 to be subtracted at the
                 # beginning of the next iteration, so that when we exit this loop,
                 # the remainder \4 is readily accessible.
)+               # Iterate the above loop any number of times, minimum one. Every
                 # number of possible iterations will be tried, meaning that the
                 # loop can exit after any iteration count, meaning the matching
                 # done after the loop will be applied to each digit in turn, with
                 # each adding linearly to the number of possible matches.
\2               # tail = tail - \2 = \4
# Each time we reach this point, tail = one of the digits of the number
x+               # Add \4 to the number of possible matches. This, and the number
                 # of iterations the above loop can do, are the only choices
                 # available for making a complete match.

Merely calculating the sum of digits of the input number N (instead of the sum of all sums of digits of 1 to N) actually takes a regex 1 byte longer, with a ^ anchor inserted at the beginning: Try it online!

This regex apparently exposes a bug in the obsolete regex engine PCRE1: Try it online! - the results start being incorrect from 10 onward.

Calculating the product of the of digits N is also 33 bytes:

^((?=(x*)(\2{9}))\3x*x+(?=\2$))+$

Try it online!

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

C# (108)

int c(int n){return string.Join("",Enumerable.Range(1,n).Select(i=>i+"")).ToArray().Select(c=>c-'0').Sum();}

Pretty

int c(int n)
{
    return string.Join("", Enumerable.Range(1, n).Select(i => i + "")).ToArray().Select(c => c - '0').Sum();
}
\$\endgroup\$
2
  • 3
    \$\begingroup\$ It is not a valid answer as it is function and char count is kind a big \$\endgroup\$
    – ST3
    Commented Jan 15, 2014 at 20:50
  • 1
    \$\begingroup\$ You don't need the ints; in C, everything defaults to int... Oh, it's C#. \$\endgroup\$
    – wizzwizz4
    Commented Mar 9, 2016 at 19:28
1
\$\begingroup\$

Ruby -> 83-50 = 33

p (1..eval(gets.chomp)).each.inject{|c,e|c+e.to_s.chars.map{|x|x.to_i}.inject(:+)}                     

"To test" version:

module Math
  class CountSum
    def sum(number)
      (1..number).each.inject do |c, e|
        c + e.to_s.chars.map{ |x| x.to_i }.inject(:+)                                                  
      end
    end
  end
end 

Tests results

$ rspec sum_spec.rb  --format doc --color

Math::CountSum
  #sum
    single digit number
      when 5, should return 15
    double digit number
      when 12, should return 51
    arbitrary number
      when 1000000 should return 27000001

Finished in 5.34 seconds
3 examples, 0 failures
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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