Take the 2-minute tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

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.

Winner will be the lowest-scoring submission on February 1st.

HELP!!!

Hey, I need some help, can you guys look through these 4 posts: 1. 2. 3. 4.

Asking this, because it is potensial winners, however not sure if they are, their code gives me some doubt, comment these and I'll set a winner in a few days, sorry for a delay.

share|improve this question
2  
And what should 55*96-12 return? –  ProgramFOX Jan 15 at 18:04
1  
55*96-12=5268, should be the same output as entered 5268 –  ST3 Jan 15 at 19:07
1  
Bonuses may be a bit on the big side, seems to be becoming a competition on the biggest negative score :) –  Joachim Isaksson Jan 15 at 19:12
2  
@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 at 19:17
1  
A complete set of 0-9 adds up to 45. A complete set of 0-99 is 45*110. A complete set of 0-999 is 45*11100. Optimizations exist if one cared about performance rather than codesize. –  keshlam Jan 16 at 4:19
show 16 more comments

56 Answers

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

share|improve this answer
    
You should add info on the valid arguments to get all brownie points :D –  Yves Klett Jan 15 at 18:48
1  
I don't know if I would consider that not using eval –  Cruncher Jan 15 at 19:19
2  
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. –  Michael Stern Jan 15 at 20:46
1  
Tr@Flatten can be reduced to Total[...,2]: IntegerDigits@Range@#~Total~2&. –  ybeltukov Jan 15 at 23:40
1  
Don't you handle arbitrarily large int and deserve another -25? –  aka.nice Jan 16 at 0:33
show 6 more comments

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: http://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.

share|improve this answer
1  
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. –  FireFly Jan 15 at 23:13
    
@FireFly I modified the answer to reflect this fact. –  Josh Jan 16 at 13:55
    
@Josh - please provide answer for 2^64 - 5 –  SergeyS Jan 19 at 12:24
add comment

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
share|improve this answer
add comment

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 1E99 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).

share|improve this answer
1  
best answer for this question I think. using a calculator language to write a code golf answer for adding numbers together. so cool! –  Malachi Jan 15 at 22:29
1  
@Malachi As I always say, when code golf = math, it's time to pull out the calculator. –  Timtech Jan 15 at 22:29
1  
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. –  FireFly Jan 15 at 23:02
1  
Agree with FireFly, bonus of not using eval shouldn't be taken. –  ST3 Jan 16 at 7:17
3  
How is a calculator not a computer? –  David Conrad Jan 16 at 18:25
show 1 more comment

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
share|improve this answer
    
I get an overflow error when I try running your xrange solution on 1234567891234567891234564789087414984894900000000 –  Josh Jan 15 at 18:38
1  
@Josh got rid of xrange :D –  Wasi Jan 15 at 18:58
2  
Some hints: You can replace eval(raw_input()) by input(). The while loop could be while t:s+=sum(map(int,t`));t-=1`. –  WolframH Jan 15 at 22:44
2  
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!!! –  Lego Stormtroopr Jan 15 at 22:44
    
@LegoStormtroopr the rules say eval and similar, so I think the -100 wouldn't count –  SztupY Jan 15 at 23:41
show 5 more comments

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);}
share|improve this answer
    
All positive integers mean, that it should handle even longer then 99 digits numbers. –  ST3 Jan 15 at 20:34
    
@Firefly cool algorithm to work on numbers larger than the builtin numerics! –  Josh Jan 15 at 20:40
add comment

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.

share|improve this answer
    
Does it support ^ as well? –  SztupY Jan 16 at 9:55
    
It supports exponentiation in GolfScript syntax, which is ? –  Ben Reich Jan 16 at 14:45
    
You do not get bonus 10, because program must support ^, not ? or pow and etc. –  ST3 Jan 16 at 19:31
    
@ST3 As you wish! –  Ben Reich Jan 16 at 19:43
add comment

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?

share|improve this answer
    
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? –  ST3 Feb 11 at 11:14
    
@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. –  xfix Feb 11 at 18:55
add comment

Perl 31 - No bonuses

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

Sample output:

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

Perl -15 (35 - 50)

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

Sample output:

perl -e 'map{s/./$%+=$&/ge}0..eval<>;print$%'
55*96-12
81393
share|improve this answer
add comment

Scala 66

println((1 to readLine().toInt).flatMap(x=>(x+"").map(_-'0')).sum)
share|improve this answer
add comment

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.

share|improve this answer
    
You can remove a few chars: p"#{[*1..eval(gets)]}".chars.map(&:to_i).inject :+ –  SztupY Jan 15 at 23:47
    
@SztupY good call, thanks! I don't use & nearly enough in golf. In fact, you don't need the space between inject and :+ either. –  Chron Jan 15 at 23:54
add comment

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

share|improve this answer
    
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. –  FireFly Jan 16 at 13:47
    
Nice answer! It is similar into the way I counted, that would be if input is 1000000 :) –  ST3 Jan 16 at 19:35
1  
+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. –  WolframH Jan 17 at 21:55
1  
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)). –  WolframH Jan 17 at 22:23
1  
@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. –  WolframH Jan 18 at 20:39
show 2 more comments

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.

share|improve this answer
    
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). –  xfix Mar 12 at 8:05
    
@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 –  Mouq Mar 12 at 22:34
    
Ohh, the $! would help get rid of the 'my '! Thanks @xfix –  Mouq Mar 16 at 17:43
add comment

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
share|improve this answer
    
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. –  Gareth Jan 16 at 6:56
    
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. –  Gareth Jan 16 at 7:00
    
This +/,10#.inv>:i. would be shorter. But it still a function and not a complete program as OP asked. –  swish Jan 16 at 17:27
    
@Gareth Bonuses don't apply to this answer, because you would just write expressions inside code and not as input. –  swish Jan 16 at 17:33
1  
@swish That's what I thought at first, but the Mathematica answer seems to work much like this. –  Gareth Jan 16 at 18:52
show 1 more comment

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.

share|improve this answer
1  
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. :-) –  Mark Jan 16 at 19:00
    
Oops, I see now why you kept your temp variable (for the bonus points). The PowerShell tip still stands, though... –  Mark Jan 16 at 20:06
    
Well spotted, Thanks. Will change that now. –  unclemeat Jan 16 at 21:37
    
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. –  Iszi Jan 16 at 22:52
1  
I will give Batch some good credit for defaulting to integer division, though. That's something PowerShell is missing entirely. –  Iszi Jan 16 at 22:59
show 2 more comments

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();
}
share|improve this answer
3  
It is not a valid answer as it is function and char count is kind a big –  ST3 Jan 15 at 20:50
add comment

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
share|improve this answer
add comment

C# (80)

Its my another attempt.

double c(int n){double s=0;while(n>0)foreach(var c in n--+"")s+=c-48;return s;}

Pretty

double c(int n)
{
    double s = 0;
     while (n > 0)
        foreach(var c in n--+"") 
            s += c - 48;
    return s;
}
share|improve this answer
    
Is the whitespace between n-- and + needed? I don't think it is in other C-style languages. –  FireFly Jan 15 at 18:54
1  
Does this work with the given range? The result for 2^64-1 doesn't fit in 64 bits. –  marinus Jan 15 at 19:38
2  
It is not a valid answer as it is function and char count is kind a big. –  ST3 Jan 15 at 20:49
    
@marinus Can you give us the result for 2^64-1 so that we can know what range we need to work with? I dare not test it in my language (PowerShell) since the processing time would be enormous. –  Iszi Jan 17 at 14:36
    
@Iszi: I'm not going to actually run it, but you can do some math: 1) the average value of a digit is 4.5; 2) the average sum of 20 digits is 90 (2^64 has 20 digits); so the expected value will be around 90 * 2^64 ≈ 1.66*10^21. So you'd need at least 71 bits, at most 72. –  marinus Jan 21 at 1:07
add comment

Ruby 69-50 = 19 (or -4)

This can definitely be golfed together but here is the first fifth try

p (1..eval(gets)).inject{|i,s|i+=s.to_s.chars.map(&:to_i).inject :+}

It also works for all numbers but is very slow for them as it runs slower than O(n), so I wouldn't add the -25. If slowness is fine, then it would be -4 though

Ruby 133-50-25 = 58

This is the faster version, that runs in less-than O(n) time (and uses actual math!), so it can provide results for large integers fast, thereby I added the -25:

n=eval(gets);p (d=->n,l{k=10**l;c,r=n.to_s[0].to_i,n%k;n<10?n*(n+1)/2:c*45*l*k/10+k*(c*(c-1)/2)+(r+1)*c+d[r,l-1]})[n,n.to_s.length-1]
share|improve this answer
    
We write exactly the same code (you golfed a little more)! –  Beterraba Jan 15 at 22:03
    
@Beterraba yup, and almost the same time, but you were a bit faster, so I have to figure out something different :) –  SztupY Jan 15 at 22:04
add comment

Haskell, 74-25=49

main=getLine>>=print.sum.map(\c->read[c]).concatMap show.(\x->[0..x]).read

share|improve this answer
    
Using interact and the fact that >>= for lists is the same as flip concatMap, you can golf this down to 63 chars like this: main=interact$show.sum.map(\c->read[c]). \x->[0..read x]>>=show –  Flonk yesterday
add comment

ECMAScript 6, 86 - 50 = 36

for(s="",i=eval(prompt());i;s+=i--)alert(s.replace(/\d/g,c=>Array(-~c).join()).length)
share|improve this answer
    
One character less: for(i=eval(prompt(s=""));i;s+=i--)alert(s.replace(/\d/g,c=>Array(-~c).join()).l‌​ength). –  toothbrush Feb 22 at 20:50
    
Quite a bit smaller (you don't need the .join()): for(i=eval(prompt(s=""));i;s+=i--)alert(s.replace(/\d/g,c=>Array(-~c)).length)‌​. 78 - 50 = 28! –  toothbrush Feb 22 at 21:17
add comment

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)
            );
    }
}
share|improve this answer
add comment

K, 16 - 50 = -34

{+/"J"$',/$!1+x}
share|improve this answer
add comment

Javascript (Paste it to your browser console):

i=eval(prompt());s=0;for(x=1;x<=i;x++){y=x;while(y>=10){s+=(t=y%10);y=(y-t)/10}s+=y}alert(s)

Eligible only for: "Can handle expressions: 50 bonus";

Code length: 92 bytes. Expected final score: 92-50=44

Ps: That's my first participation on this, so please tell me if I'm doing anything wrong.

share|improve this answer
add comment

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)
share|improve this answer
    
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. –  Carl Witthoft Jan 16 at 16:13
    
@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. –  Sven Hohenstein Jan 16 at 16:28
    
so if I create a Rcheatcodegolf package, is it legal to use the predefined functions in that package? :-) –  Carl Witthoft Jan 16 at 16:34
    
@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. –  Sven Hohenstein Jan 16 at 16:52
add comment

PowerShell: 55

Mainly derived from this answer by microbian but with enough golfing and bug fixes I figured it was worth posting separately.

The script is 55 characters long. A previous version had claimed functionality for handling expressions, (thus a -50 bonus) but then I remembered that PowerShell doesn't do integer division by default. This would not meet the specification for the bonus, and would probably produce erroneous results whenever there is a remainder in a division operation. Adding the code needed to properly force integer division would probably not be worth the bonus.

Warning: This script should theoretically be able to handle any input for which the output is up to (2^96)-1. However, any input larger than about 5 digits is going to take a fairly long time to process.

This can be saved and run as a script, or run straight from the PowerShell console. The golfed version is a little "messy" - use rv x,y in between runs for variable cleanup.

Golfed Code:

for($x=read-host;$x;$x-=1){[char[]]"$x"|%{$y+=$_-48}}$y

Un-Golfed & Commented:

# Begin for loop definition.
for(
    # Take input from the user and store it in $x.
    # We don't need to explicitly force $x to any particular integer type, because PowerShell will automatically choose an appropriate type according to the result of an expression when math operators are used.
    # This piece should be able to handle inputs which evaluate as large as (2^96)-1.
    $x=read-host;
    # Loop runs so long as $x remains greater than zero since any non-zero values for $x are treated as $true.
    $x;
    # $x is decremented by one every time the loop runs.
    # I needed to use $x-=1 instead of $x-- because $x initially starts as a string, so the latter operator would not be available. $x-=1 will force $x into a number type.
    $x-=1
)
{
    # Convert $x to a string, then to a character array, and pass the array to ForEach-Object (%).
    [char[]]"$x"|%{
        # Increment $y by the integer value of the current character, minus 48.
        # Taking out 48 is needed to account for the difference in the digits' values and their ASCII codes.
        # We don't need to explicitly force a type on the current character, as the increment operator will automatically cast it to an integer.
        # We also don't need to explicitly force a type on $y, as the increment operator will do that appropriately for us so long as it is not hard-set otherwise.
        # This should be able to handle values of $y up to (2^96)-1.
        $y+=$_-48
    }
}
# After all loops are done, output $y.
$y

# Variables cleanup. Not included in golfed code.
rv x,y

I have tested this against the cases given in the question (inputs of 5, 10, 12, 5268, and 1000000) and they all gave the expected correct outputs. I dare not try testing it much higher due to performance issues.

share|improve this answer
    
Why not 1..(read-host|iex)|%... instead of the for loop? –  Danko Durbić Jan 16 at 13:45
    
@DankoDurbić I tried that, but it requires that the result of (read-host|iex) fits within an int32. The question requires handling of values at least up to the maximum of a uint64. –  Iszi Jan 16 at 14:50
    
Oh, I see. Still, you can shorten the condition in the loop to just $x instead of $x-gt0. –  Danko Durbić Jan 16 at 15:45
    
@DankoDurbić Good catch. Thanks. –  Iszi Jan 16 at 16:00
    
Shave off one character by using args[0] and parsing the value when calling the script, instead of read-host. for($x=$args[0];$x;$x-=1){[char[]]"$x"|%{$y+=$_-48}}$y –  unclemeat Jan 21 at 1:09
show 1 more comment

Golf, 38, 33-25=8

~,{1+}/]{''+[{-48+}/]{+}*}/]{+}*

This is my first (still very verbose) attempt at Golfscript.

Explanation:

~, -> converts input into a number (n), and creates an array of n elements starting at 0

{1+}/ -> adds one to all the elements of the previous array

] -> converts to an array

{''+[{-48+}/]{+}*}/ -> this is a function, applied to all the elements of the previous array, that:

''+ -> turns the array in an array of strings

{-48+}/ -> subtracts 48 ('0') from each element of the array

{+}* -> sums all the elements of the array

At the end, the {+}* sums all the results of the previous calculations, giving the correct output.

share|improve this answer
add comment

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.

share|improve this answer
    
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! –  Tobia Jan 16 at 21:24
    
Agree with @Tobia, no bonus for expression evaluator. –  ST3 Feb 3 at 8:43
add comment

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.

share|improve this answer
add comment

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));
  }
}
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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