Count sum of all digits

38

11

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.

ST3

Posted 2014-01-15T17:39:59.620

Reputation: 1 279

There's also some, like JavaScript, that physically can't do that requirement. – Isiah Meadows – 2015-01-31T07:46:02.960

2And what should 55*96-12 return? – ProgramFOX – 2014-01-15T18:04:02.247

155*96-12=5268, should be the same output as entered 5268 – ST3 – 2014-01-15T19:07:16.337

3Bonuses may be a bit on the big side, seems to be becoming a competition on the biggest negative score :) – Joachim Isaksson – 2014-01-15T19:12:42.720

Possibly, however, I have set them, so it wouldn't be fair to change it, as there are some answers, anyway, winner probably will have all bonuses and the shortest code. – ST3 – 2014-01-15T19:15:50.323

7@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 – 2014-01-15T19:17:00.797

@Cruncher they could still matter for intra-language competition – FireFly – 2014-01-15T19:35:59.803

1Do you want a program or a function? Some guys are posting functions, so I don't know if this is acceptable. – Gabriele D'Antona – 2014-01-15T20:10:50.173

Would it be acceptable to take input on the command-line (as arguments) instead of stdin? – FireFly – 2014-01-15T20:34:17.083

@FireFly edited – ST3 – 2014-01-15T20:38:15.327

1A complete set of 0-9 adds up to 45. A complete set of 0-99 is 45110. A complete set of 0-999 is 4511100. Optimizations exist if one cared about performance rather than codesize. – keshlam – 2014-01-16T04:19:26.203

1@keshlam: if there'd be a proper incentive about performance (e.g. it has to run for very large numbers in decent time, and the bonus for this would be higher) then maybe there'd be more solutions. At the moment there are only two efficient solutions here as far as I can tell – SztupY – 2014-01-16T09:52:55.423

Almost everyone could shorten their solution by using the closed form 1+2+...+n=n*(n+1)/2. – flonk – 2014-01-16T12:13:09.803

1@flonk: This is wrong. Why people don't read tasks, I wonder. I decided to put a note in task (as an edit). Seriously, this is not task about summing numbers. – Konrad Borowski – 2014-01-16T12:35:59.767

1@xfix Thank you for pointing out my mistake. I can't give you a satisfying answer why "people" don't read tasks, but in my personal case the reason is simply that I only do this for procrastination, so only a small part of my brain is really able to focus on PCG. – flonk – 2014-01-16T13:26:32.240

1Do we get the bonus if it processes postfix expressions? (e.g. 3 4 + 2 * = 14) – AJMansfield – 2014-01-16T16:17:08.890

I'd say postfix should count. As long as it's clearly defined syntax... – keshlam – 2014-01-16T18:29:15.687

@ST3 Does my answer (Batch) qualify for the -100 bonus?

– unclemeat – 2014-01-16T22:26:24.523

Obviously, if I wasn't already disqualified. – unclemeat – 2014-01-16T23:16:09.017

Anybody have an answer for that? – unclemeat – 2014-01-17T03:07:24.033

@ST3 - if you stated that input up to 2^64, than you should have answer for all numbers up to 2^64, and people who answer need to provide output for such big numbers, so that you can judge whether their solutions are correct. – SergeyS – 2014-01-19T12:20:23.713

How relies upon any web resources is a penalty, not disallow? – l4m2 – 2018-03-21T07:55:40.507

3-1 because this challenge uses the outdated (and awful) scoring incentive of "bonuses". – mbomb007 – 2018-05-09T21:23:22.810

+1 for the idea, but -1 for the second and third bonus, that's a whole different problem. That equals 0 from me. – nyuszika7h – 2014-09-19T20:16:07.220

I bet that many solutions did not test "The code must be able to properly handle inputs at least up to (2^64)-1.". So who guarantees that all solutions are tested/treated equally? How can a fair judgement be guaranteed? – None – 2014-09-21T07:33:08.410

Please try python -c 'print xrange(2**64)'. Python2 complains OverflowError: long int too large to convert to int so a Python2 solution relying on xrange() (or range() for other reasons too) to generate 1...InputNumber breaks "The code must be able to properly handle inputs at least up to (2^64)-1.". Noone seems to complain about this... or am I wrong with ihis conclusion?¿? – None – 2014-09-23T09:30:18.250

@yeti The question should probably be fixed, this requirement is either a mistake or fairly arbitrary. The biggest 64-bit integer is (2^63)-1, which Python can handle fine. It seems to me that technically any solution that can handle (2^64)-1 would qualify for the -25 bonus as well. – nyuszika7h – 2014-09-23T18:33:24.917

Answers

9

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.

Mouq

Posted 2014-01-15T17:39:59.620

Reputation: 906

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). – Konrad Borowski – 2014-03-12T08:05:12.597

@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 – 2014-03-12T22:34:46.353

Ohh, the $! would help get rid of the 'my '! Thanks @xfix – Mouq – 2014-03-16T17:43:11.550

14

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

DavidC

Posted 2014-01-15T17:39:59.620

Reputation: 24 524

You should add info on the valid arguments to get all brownie points :D – Yves Klett – 2014-01-15T18:48:20.113

Yes, I'm working on that now. It requires a variation on the initial approach. – DavidC – 2014-01-15T18:52:39.120

1I don't know if I would consider that not using eval – Cruncher – 2014-01-15T19:19:17.053

I'm not familiar with Mathematica, but I think your score is to good to be true. You didn't implement expression calculation yourself, so I give you -26 instead of -126. – ST3 – 2014-01-15T20:32:42.023

fine. I'll make the change. – DavidC – 2014-01-15T20:44:38.447

3re: 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 – 2014-01-15T20:46:38.393

@Michael great comment, I'll keep it in mind, because it may be useful one day :) – ST3 – 2014-01-15T20:47:56.257

1Tr@Flatten can be reduced to Total[...,2]: IntegerDigits@Range@#~Total~2&. – ybeltukov – 2014-01-15T23:40:37.190

1Don't you handle arbitrarily large int and deserve another -25? – aka.nice – 2014-01-16T00:33:41.007

Thanks, I hadn't seen that use of Total. – DavidC – 2014-01-16T00:56:13.710

aka.nice, there are limits to what Range can handle. My code returns an incorrect answer for the suggested large integer. – DavidC – 2014-01-16T00:57:54.687

12

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.

Josh

Posted 2014-01-15T17:39:59.620

Reputation: 2 783

1This 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 – 2014-01-15T23:13:16.730

@FireFly I modified the answer to reflect this fact. – Josh – 2014-01-16T13:55:41.953

@Josh - please provide answer for 2^64 - 5 – SergeyS – 2014-01-19T12:24:04.760

10

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

FireFly

Posted 2014-01-15T17:39:59.620

Reputation: 7 107

8

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

Wasi

Posted 2014-01-15T17:39:59.620

Reputation: 1 682

I get an overflow error when I try running your xrange solution on 1234567891234567891234564789087414984894900000000 – Josh – 2014-01-15T18:38:46.773

1@Josh got rid of xrange :D – Wasi – 2014-01-15T18:58:13.450

2Some hints: You can replace eval(raw_input()) by input(). The while loop could be while t:s+=sum(map(int,t));t-=1. – Reinstate Monica – 2014-01-15T22:44:16.360

2You 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!!! – None – 2014-01-15T22:44:23.737

@LegoStormtroopr the rules say eval and similar, so I think the -100 wouldn't count – SztupY – 2014-01-15T23:41:18.223

Your first code doesn't allow large integers on py2.7 and doesn't compile on py3.3. Which version should I try? – SztupY – 2014-01-15T23:44:31.120

@SztupY: In order to work on Python 2.7, you have to remove the brackets, like WolframH suggests. – Gabe – 2014-01-16T07:25:57.783

@Gabe Yap! I just edited the body. So, It should work now :) – Wasi – 2014-01-16T07:30:05.310

The faster method was a bit inefficient. I shaved 10 strokes off (I think). – Gabe – 2014-01-16T07:48:08.300

Does the inefficient version run in decent time for the large number? If not I don't think you can count the -25 – SztupY – 2014-01-16T09:50:54.603

8

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

Timtech

Posted 2014-01-15T17:39:59.620

Reputation: 12 038

-1; doesn't work and can't work even if fixed for numbers greater than 999 (the greatest possible list size). – lirtosiast – 2015-06-07T14:55:46.680

I always upvote TI-Basic :) – Naveen Arun – 2016-08-30T23:12:56.260

@NaveenArun Cool! – Timtech – 2016-08-31T16:56:54.413

1best answer for this question I think. using a calculator language to write a code golf answer for adding numbers together. so cool! – Malachi – 2014-01-15T22:29:07.970

1@Malachi As I always say, when code golf = math, it's time to pull out the calculator. – Timtech – 2014-01-15T22:29:47.957

2My 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 – 2014-01-15T23:02:13.300

@FireFly Aww :( Okay – Timtech – 2014-01-15T23:13:23.650

1Agree with FireFly, bonus of not using eval shouldn't be taken. – ST3 – 2014-01-16T07:17:26.927

3How is a calculator not a computer? – David Conrad – 2014-01-16T18:25:33.013

8

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

ymbirtt

Posted 2014-01-15T17:39:59.620

Reputation: 1 792

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 – 2014-01-16T13:47:31.393

Nice answer! It is similar into the way I counted, that would be if input is 1000000 :) – ST3 – 2014-01-16T19:35:25.173

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. – Reinstate Monica – 2014-01-17T21:55:59.967

1Golfing 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)). – Reinstate Monica – 2014-01-17T22:23:10.060

@WolframH Is that how that works? I was wondering how best to stop Python from turning things to floats in a short way. Thanks for the tips, I'd never even seen the tilde operator before. – ymbirtt – 2014-01-18T10:37:47.983

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. – Reinstate Monica – 2014-01-18T20:39:31.920

@WolframH Ohhhhh, that's why that was happening. OK, thanks for spotting that. – ymbirtt – 2014-01-18T21:51:45.450

It looks like there's some loss of precision in this due to floating point issues - it returns the same output for 999999999999999 and 1000000000000001 (67500000000000000) for eg., and the output for the very large number is also different from mine, duedl0r's, Wasi's (which all give 265889343871444899381999757086453238874482500000214).

– sundar - Reinstate Monica – 2018-07-10T11:09:34.790

The "golfed" version doesn't seem equivalent to the full code either - it returns completely wrong answers for any of these large numbers (looks more like overflow than loss of precision in this case). It looks like Python can easily handle arbitrarily large integers, but replacing the ints with longs in the code didn't help, and I don't know enough Python to know where the overflow/precision loss is coming from.

– sundar - Reinstate Monica – 2018-07-10T11:42:03.310

6

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);}

FireFly

Posted 2014-01-15T17:39:59.620

Reputation: 7 107

All positive integers mean, that it should handle even longer then 99 digits numbers. – ST3 – 2014-01-15T20:34:09.543

@Firefly cool algorithm to work on numbers larger than the builtin numerics! – Josh – 2014-01-15T20:40:55.603

6

Scala 66

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

ValarDohaeris

Posted 2014-01-15T17:39:59.620

Reputation: 231

5

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.

Ben Reich

Posted 2014-01-15T17:39:59.620

Reputation: 1 577

Does it support ^ as well? – SztupY – 2014-01-16T09:55:03.747

It supports exponentiation in GolfScript syntax, which is ? – Ben Reich – 2014-01-16T14:45:49.103

You do not get bonus 10, because program must support ^, not ? or pow and etc. – ST3 – 2014-01-16T19:31:23.493

@ST3 As you wish! – Ben Reich – 2014-01-16T19:43:22.923

4

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!

Dom Hastings

Posted 2014-01-15T17:39:59.620

Reputation: 16 415

4

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.

Paul Prestidge

Posted 2014-01-15T17:39:59.620

Reputation: 2 390

You can remove a few chars: p"#{[*1..eval(gets)]}".chars.map(&:to_i).inject :+ – SztupY – 2014-01-15T23:47:10.650

@SztupY good call, thanks! I don't use & nearly enough in golf. In fact, you don't need the space between inject and :+ either. – Paul Prestidge – 2014-01-15T23:54:38.767

4

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?

Konrad Borowski

Posted 2014-01-15T17:39:59.620

Reputation: 11 185

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 – 2014-02-11T11:14:51.570

@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. – Konrad Borowski – 2014-02-11T18:55:01.610

couldn't you use get.Int instead of eval ? Does it need math expressions ? – Ven – 2014-04-18T08:57:57.553

@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). – Konrad Borowski – 2014-04-18T12:34:11.223

3

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

DevonMcC

Posted 2014-01-15T17:39:59.620

Reputation: 79

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 – 2014-01-16T06:56:01.733

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 – 2014-01-16T07:00:34.923

This +/,10#.inv>:i. would be shorter. But it still a function and not a complete program as OP asked. – swish – 2014-01-16T17:27:29.207

@Gareth Bonuses don't apply to this answer, because you would just write expressions inside code and not as input. – swish – 2014-01-16T17:33:15.237

1@swish That's what I thought at first, but the Mathematica answer seems to work much like this. – Gareth – 2014-01-16T18:52:59.703

Writing this as +/@([:"."0@":1+i.) saves 4 chars with no change in functionality, putting the entry at 18 (or -42, if the bonuses hold). – algorithmshark – 2014-01-17T05:02:21.010

3

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.

unclemeat

Posted 2014-01-15T17:39:59.620

Reputation: 2 302

1Nice 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 – 2014-01-16T19:00:24.313

Oops, I see now why you kept your temp variable (for the bonus points). The PowerShell tip still stands, though... – Mark – 2014-01-16T20:06:24.847

Well spotted, Thanks. Will change that now. – unclemeat – 2014-01-16T21:37:49.000

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 – 2014-01-16T22:52:02.047

1I will give Batch some good credit for defaulting to integer division, though. That's something PowerShell is missing entirely. – Iszi – 2014-01-16T22:59:01.030

Haha, of course, I just like doing challenges that batch is really not suited for. – unclemeat – 2014-01-16T23:01:48.527

Does this answer qualify for the -100 bonus? – unclemeat – 2014-01-17T01:41:10.240

3

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)

Sven Hohenstein

Posted 2014-01-15T17:39:59.620

Reputation: 2 464

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 – 2014-01-16T16:13:38.090

@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 – 2014-01-16T16:28:57.213

so if I create a Rcheatcodegolf package, is it legal to use the predefined functions in that package? :-) – Carl Witthoft – 2014-01-16T16:34:07.723

@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 – 2014-01-16T16:52:10.640

3

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

Adám

Posted 2014-01-15T17:39:59.620

Reputation: 37 779

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). – Kevin Cruijssen – 2018-10-09T11:56:59.233

@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. – Adám – 2018-10-09T12:00:21.817

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? – Kevin Cruijssen – 2018-10-09T12:06:50.527

1@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. – Adám – 2018-10-09T12:19:22.117

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. – Kevin Cruijssen – 2018-10-09T12:22:52.493

2

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)
            );
    }
}

Firo

Posted 2014-01-15T17:39:59.620

Reputation: 121

2

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.

Stefano Sanfilippo

Posted 2014-01-15T17:39:59.620

Reputation: 1 059

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 – 2014-01-16T21:24:17.433

Agree with @Tobia, no bonus for expression evaluator. – ST3 – 2014-02-03T08:43:33.480

2

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.

Sri

Posted 2014-01-15T17:39:59.620

Reputation: 21

2

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));
  }
}

whyem

Posted 2014-01-15T17:39:59.620

Reputation: 123

+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. – user902383 – 2016-07-28T13:09:54.117

2

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.

Martin Ender

Posted 2014-01-15T17:39:59.620

Reputation: 184 808

2

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

user36215

Posted 2014-01-15T17:39:59.620

Reputation:

This is amazing, but yet horrifying. Not sure if it's allowed (to knowingly use a long solution), but 10/10 from me. – Rɪᴋᴇʀ – 2016-06-23T22:35:25.510

@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 ;) – None – 2016-06-23T23:15:46.100

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. – Rɪᴋᴇʀ – 2016-06-24T02:18:00.830

@EᴀsᴛᴇʀʟʏIʀᴋ Now I'm curious, who was that user? – cat – 2016-06-30T23:29:40.967

1@cat An arabic name I couldn't pronounce? Probably nuked account. – Rɪᴋᴇʀ – 2016-07-02T12:28:00.243

1

Julia 0.6, -7 bytes (53 - 50 - 10) bytes

/ =÷
show(sum(sum.(digits.(1:eval(parse(ARGS[]))))))

Try it online!

Plain and simple - construct an array containing all the digits of the number in the range, sum the digits of individual numbers elementwise, then sum those digit sums together. The / =÷ reassigns / to be integer division, since otherwise eval will treat / in input as float division (and OP specifies "Division is regular integer division").

Because this constructs an array of array of all the digits in the range, this becomes very memory hungry for larger numbers. A better, much faster version is:

Julia 0.6, 39 (124 - 25 - 50 - 10) bytes, handles very large inputs

/ =÷
!n=n<=9?(n+1)n/2:(v=n/(t=10^(d=big(ndigits(n)-1))))*45d*10^~-d+t*(v-1)v/2+(1+n%t)v+!(n%t)
show(!(eval(parse(ARGS[]))))

Try it online!

This can handle inputs upto and above 1234567891234567891234564789087414984894900000000 very quickly.

julia> @btime !1234567891234567891234564789087414984894900000000
  282.726 μs (3167 allocations: 80.43 KiB)
265889343871444899381999757086453238874482500000214

I couldn't understand @ymbirtt's explanation of their Python code, and so set out to find a way of calculating this myself - and it looks like I rediscovered the method Wasi uses in their answer.

But because this uses BigInts and not floats, there's no loss of precision in large numbers - for eg., the Python code in ymbirtt's answer gives the same output for 999999999999999 and 1000000000000001 (67500000000000000), while this Julia version correctly returns 67500000000000000 and 67500000000000003 respectively. (This lead to some wall-meet-head moments while debugging my code before I realized what was happening, since I was using their Python code's output as the reference output to check against.) Two other answers with correct output for the very large number are duedl0r's Haskell answer (which I couldn't figure out how to run on TIO) and Wasi's Python answer (TIO).

Ungolfed with explanation:

# reassign float division to integer division (for the eval and to save bytes otherwise)
/ =÷
function f_(n::BigInt)
  # necessary as a base case for the recursion
  n <= 9 && return (n+1)n÷2
  d = big(ndigits(n)-1)
  # highest power of ten that's less than n
  # say n is 4895, then t = 1000
  t = 10^d
  # get first digit of n (v = 4 in this case)
  v = n÷t
  # initialize digit sum
  s = big(0)
  # there have been 1000 1's, 1000 2's, and 1000 3's as first digits of numbers so far,
  #  add those to the digit sum
  s += t*(v-1)v÷2
  # now that the first digits upto 3999 are taken care of, handle the other digits
  # digits in 0 to 3999 = digits in 0000 to 0999 + in 1000 to 1999 +
  # in 2000 to 2999 + in 3000 to 3999
  # once first digits are taken care of, that becomes four times the digits in 0 to 999
  # in 0 to 999, 6 occurs 100 times in hundreds digit (600-699),
  # 100 times in tens digit (x60 to x69, for x from 0 to 9),
  # 100 times in ones digit (xy6 for x from 0 to 9, for y from 0 to 9)
  # so 6 occurs 3*10^2 times in 0 to 999, or in general d*10^(d-1) times
  # so sum of 6s in 0 to 999 is 6d*10^(d-1), and since we have to consider
  # that range four times, sum in 0 to 3999 is 4*6d*10^(d-1)
  # same logic applies for the other digits, so the sum of all non-first digits
  # in this range (0 to 3999) is: 4*1d*10^(d-1) + 4*2d*10^(d-1) + ... 4*9d*10^(d-1)
  # = 4*(1+2+...+9)*d*10^(d-1) = 4*45d*10^(d-1)
  # or in general, v*45d*10^(d-1)
  s += v*45d*10^(d-1)
  #sum of digits up to 3999 has been taken care of

  # now sum from 4000 to 4895
  # there are 896 4s in the first digit in this range, so sum of those is 4*896
  # or in general, v*(1 + n%t)
  s += v*(1+n%t)
  # first digit taken care of, now call this function recursively to find sum of 
  # digits in 0 to 895 (which is all that remains to be summed)
  s += f_(n%t)
end
isinteractive() || show(f_(big(eval(parse(ARGS[])))))

sundar - Reinstate Monica

Posted 2014-01-15T17:39:59.620

Reputation: 5 296

1

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();
}

microbian

Posted 2014-01-15T17:39:59.620

Reputation: 2 297

1You don't need the ints; in C, everything defaults to int... Oh, it's C#. – wizzwizz4 – 2016-03-09T19:28:30.460

3It is not a valid answer as it is function and char count is kind a big – ST3 – 2014-01-15T20:50:07.563

1

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;
}

microbian

Posted 2014-01-15T17:39:59.620

Reputation: 2 297

Is the whitespace between n-- and + needed? I don't think it is in other C-style languages. – FireFly – 2014-01-15T18:54:02.580

1Does this work with the given range? The result for 2^64-1 doesn't fit in 64 bits. – marinus – 2014-01-15T19:38:17.020

2It is not a valid answer as it is function and char count is kind a big. – ST3 – 2014-01-15T20:49:43.733

@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 – 2014-01-17T14:36:28.320

@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 – 2014-01-21T01:07:41.330

1

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

Beterraba

Posted 2014-01-15T17:39:59.620

Reputation: 111

1

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]

SztupY

Posted 2014-01-15T17:39:59.620

Reputation: 3 639

We write exactly the same code (you golfed a little more)! – Beterraba – 2014-01-15T22:03:50.280

@Beterraba yup, and almost the same time, but you were a bit faster, so I have to figure out something different :) – SztupY – 2014-01-15T22:04:41.820

1

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.

Gabriele D'Antona

Posted 2014-01-15T17:39:59.620

Reputation: 1 336

1

Haskell, 74-25=49

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

Vektorweg

Posted 2014-01-15T17:39:59.620

Reputation: 301

One more byte to save: \c->read[c] is read.(:[]) – nimi – 2015-01-19T20:56:35.900

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 – 2014-04-15T12:35:42.487

1

Javascript, 79 points 35 points 29 points 25 points

for(i=1,e=eval(prompt()),s=1;i<e;i++,s+=+eval((''+i).split('').join('+')));

From @Collin Grady's comment, 24 points

for(t=0,x=1,m=+eval(prompt());x<=m;t+=+eval((""+x++).split("").join('+')));aler‌​t(t);

This is my first serious golf, so if anyone has tips for me, I'd be glad to hear them!

scrblnrd3

Posted 2014-01-15T17:39:59.620

Reputation: 1 554

eval((''+prompt()).split('').join('+')) – None – 2014-01-16T03:28:00.680

@GabrielSantos where would I put that? – scrblnrd3 – 2014-01-16T03:37:01.970

Just open the console with CTRL+SHIFT+K and paste that code. – None – 2014-01-16T03:43:27.237

That sums the number, not all the numbers up until that point, unless I'm misunderstanding you – scrblnrd3 – 2014-01-16T03:50:15.007

Actually it's better eval((''+eval(prompt())).split('').join('+')) //

12345 => returns 15; 12*5+1 => returns 7 – None – 2014-01-16T03:56:59.457

Oops. I think I didn't read the question. – None – 2014-01-16T04:00:25.227

1

Hey @scrblnrd3, hope you're enjoying the golf! I recently read a post on meta about JS IO standards and I think you need to add an alert of s to conform in this case... However you should be able to save a few chars in its place using s=i=1 instead of s=1,i=1 and remove the i++, changing the eval((''+i) to eval((''+i++)!

– Dom Hastings – 2014-01-16T08:43:57.493

swiped some of the suggestions here: for(t=0,x=1,m=+eval(prompt());x<=m;t+=+eval((""+x++).split("").join('+')));alert(t);; 84 - 50 bonus - 10 bonus = 24 – Collin Grady – 2014-01-23T01:32:09.350

1

ECMAScript 6, 86 - 50 = 36

for(s="",i=eval(prompt());i;s+=i--)alert(s.replace(/\d/g,c=>Array(-~c).join()).length)

FireFly

Posted 2014-01-15T17:39:59.620

Reputation: 7 107

One character less: for(i=eval(prompt(s=""));i;s+=i--)alert(s.replace(/\d/g,c=>Array(-~c).join()).length). – Toothbrush – 2014-02-22T20:50:05.760

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 – 2014-02-22T21:17:32.923

1

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.

Iszi

Posted 2014-01-15T17:39:59.620

Reputation: 2 369

Why not 1..(read-host|iex)|%... instead of the for loop? – Danko Durbić – 2014-01-16T13:45:51.693

@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 – 2014-01-16T14:50:32.200

Oh, I see. Still, you can shorten the condition in the loop to just $x instead of $x-gt0. – Danko Durbić – 2014-01-16T15:45:27.987

@DankoDurbić Good catch. Thanks. – Iszi – 2014-01-16T16:00:13.117

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 – 2014-01-21T01:09:13.867

Just noticed that with that method you can also use $x-- instead of $x-=1. Bringing you down to 53. – unclemeat – 2014-01-21T01:12:50.303

1

R (72 points)

f=function(n) sum(as.integer(strsplit(paste0(1:n,collapse=""),"")[[1]]))

Output:

> f(5)
[1] 15
> f(12)
[1] 51
> f(1000000)
[1] 27000001

djhurio

Posted 2014-01-15T17:39:59.620

Reputation: 1 113

In these challenges do you need to explicitily write "f=function(n) " or just the function with n? – skan – 2016-12-19T20:41:01.017

@skan, it depends on requirements. Usually it is not required to have an explicit function. – djhurio – 2016-12-20T06:47:57.020

1

Java(454 - 25 = 429) (super bad score, yep.)

It's not very fast, but it's working and eligible for the 25 Bonus. Just felt like doing a bit recursion.~

Ugly:

import static java.math.BigInteger.*;import java.math.BigInteger;public class Summy{public static void main(String[] args){if(args.length > 0){BigInteger n, s;n = new BigInteger(args[0]);s = ZERO;for(BigInteger i = ONE; i.compareTo(n.add(ONE)) == -1; i = i.add(ONE))s = s.add(m(i));System.out.println(s.toString());}}static BigInteger m(BigInteger n){return n.compareTo(valueOf(100))==-1?n.mod(TEN).add(n.divide(TEN)):m(n.divide(TEN)).add(n.mod(TEN));}}

Easier to read:

import static java.math.BigInteger.*;
import java.math.BigInteger;
public class Summy
{
    public static void main(String[] args)
    {
        if(args.length > 0)
        {
            BigInteger n, s;n = new BigInteger(args[0]);s = ZERO;
            for(BigInteger i = ONE; i.compareTo(n.add(ONE)) == -1; i = i.add(ONE))s = s.add(m(i));
            System.out.println(s.toString());
        }
    }
    static BigInteger m(BigInteger n){return n.compareTo(valueOf(100))==-1?n.mod(TEN).add(n.divide(TEN)):m(n.divide(TEN)).add(n.mod(TEN));}
}

Leo Pflug

Posted 2014-01-15T17:39:59.620

Reputation: 185

When i started doing my java solution, i thought to get all bonus points, but in the middle, i realized it's not worth it. – user902383 – 2016-07-28T13:14:08.850

You don't have call your class Summy. S will do. – Konrad Borowski – 2014-01-16T12:52:14.580

I liked the name, since I have many lines I felt like it wouldn't matter anyway. :D – Leo Pflug – 2014-01-16T13:03:16.953

1

K, 16 - 50 = -34

{+/"J"$',/$!1+x}

tmartin

Posted 2014-01-15T17:39:59.620

Reputation: 3 917

You can get shorter with .:' instead of "J"$' without losing the eval bonus because you're using it for parsing not evaluation. – geocar – 2016-07-31T12:02:56.710

1

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.

Alexandre T.

Posted 2014-01-15T17:39:59.620

Reputation: 111

1

R5RS Scheme/Racket: 42 (227 - all bonuses)

(display(let l((s 0)(n(let e((x(read)))(if(pair? x)(apply(e(car x))(map e(cdr x)))(if(number? x)x(cadr(assoc x`((+,+)(-,-)(/,/)(*,*)(^,expt))))))))(c 0))(if(= 0 s)(if(= 0 n)c(l n(- n 1)c))(l(quotient s 10)n(+(modulo s 10)c)))))

Ungolfed:

(display 
 (let l ((s 0)
         (n (let e ((x (read)))
              (if (pair? x)
                  (apply (e (car x))
                         (map e(cdr x)))
                  (if (number? x)
                      x
                      (cadr (assoc x`((+,+)(-,-)(/,/)(*,*)(^,expt))))))))
         (c 0))
   (if (= 0 s)
       (if (= 0 n)
           c
           (l n (- n 1) c))
       (l (quotient s 10) n (+ (modulo s 10) c)))))

The mathematical expressions accepted are fully parenthesized polish prefix (LISP syntax) with the symbols demanded (^ neded rewriting). More than half the code is the interpreter.

Eg.

(+ (* 2 4) (^ 2 5)) ; == 40 ==> displays 244

Sylwester

Posted 2014-01-15T17:39:59.620

Reputation: 3 678

1

Python 59-25-50-10 (-100): -26

(or -126, again: depending on how you see P2's input()) Oh wait, xrange supports things outside of range's scope. One character extra for 25 bonus points? Sure!

 sum(sum(int(a) for a in str(b+1)) for b in xrange(input()))

Old version:

Python 58-50-10(-100): -2

(or -102, depending on how you think of Python 2's input())

sum(sum(int(a) for a in str(b+1)) for b in range(input()))

ɐɔıʇǝɥʇuʎs

Posted 2014-01-15T17:39:59.620

Reputation: 4 449

1Make your generator expression nested to save some characters: sum(int(a)for b in xrange(input())for a in str(b+1)). – Steven Rumbalski – 2016-06-20T16:55:35.303

1

Haskell - 67

f x=sum.map(read.(:[])).(=<<) show$[1..x]
main=interact$show.f.read

If you prepend f::Integer->Integer, it may qualify for a bonus (87 - 25 = 62), though it will probably OOM on large inputs.

nyuszika7h

Posted 2014-01-15T17:39:59.620

Reputation: 1 624

1

Python2 - 75 (pure filesize, bonus stuff still uncounted)

The 'x' file:

N,i,d=input(),0,0
while i<N:
 i+=1
 n=i
 while n:
  d+=n%10
  n/=10
print d

Test runs:

$ python x
5
15
$ python x
12
51
$ python x
1000000
27000001
$ python x
5268
81393
$ python x
55*96-12
81393
$ python x
32
177
$ python x
2**5
177

Test runs I did not let finish because being impatient:

$ python x
2**(64-1)
### are you patient enough?
$ python x
1234567891234567891234564789087414984894900000000
### are you patient enough?

Python should handle these two test cases because it transparently switches to variable length long integers when the fixed lenghth integer range is insufficient.

user19214

Posted 2014-01-15T17:39:59.620

Reputation:

1

Pyke, 4 - (50), -46 bytes, noncompeting

hmss

Try it here!

Blue

Posted 2014-01-15T17:39:59.620

Reputation: 26 661

Oh, for god's sake. – cat – 2016-06-30T23:30:07.420

1

PHP, 110

$a=$argv[1];$b='0';do{$b=bcadd($b,(string)array_sum(str_split($a,1)));}while(($a=bcadd($a,-1))!='0');echo $b;

PHP is certainly not the easiest language for this, but the standard library has some nice stuff inside. The code relying on bcmath to do the job of working with very large numbers, and on two functions for string splitting and summing the contents of an array. It is certainly going to run with very large numbers, but that's gonna take some time (2 minutes 9 seconds for the number 100000000).

Here's an ungolfed version:

$a = $argv[1];
$b = '0';

do {
    $b = bcadd($b, (string) array_sum(str_split($a, 1)));
}
while(($a = bcadd($a, -1)) != '0');

echo $b;

And here's another shorter version (68 bytes), but this one is going to work only until an integer overflow occurs.

$a=$b=$argv[1];while($a--){$b.=$a;}echo array_sum(str_split($b,1));

P.S: Yes, I'm a necromancer, so feel free to burn me at the stake :)

NorthBridge

Posted 2014-01-15T17:39:59.620

Reputation: 191

1

Python 3, 76 bytes - (25 + 50 + 10) = -9

Put this as a separate answer because it's not anything fancy.

Also, ** is the exponentiation operator because ^ is XOR. I believe this still qualifies for the -10 bonus.

print(sum(map(int, list("".join(map(str, range(1,eval(str(input()))+1)))))))

user36215

Posted 2014-01-15T17:39:59.620

Reputation:

1

PHP 4.1, 88-25-50=13 bytes

call in a web browser or with php-cgi; n as argument

<?for(eval('$i=$n;');$i;$i=bcsub($i,1))foreach(str_split($i)as$d)$s=bcadd($s,$d);echo$s;

Use PHP 4.1 to get off -6 of any of the current PHP versions by using $n instead of $argv[1].

current PHP: call from cli with number or calculation string as argument 1

PHP, 94-25-50=19 bytes

<?for(eval('$i=$argv[1];');$i;$i=bcsub($i,1))foreach(str_split($i)as$d)$s=bcadd($s,$d);echo$s;

69-50=19

<?for(eval('$i=$argv[1];');$i;)$s+=array_sum(str_split($i--));echo$s;

92-50-10=32 bytes

<?for(eval(str_replace('^','**',"\$i=$argv[1];"));$i;)$s+=array_sum(str_split($i--));echo$s;

201-50-10-100=41 bytes *

<?for($i=$argv[1];$p='^*/+-'[$k++];)while(preg_match("#(\d+)\\$p(\d+)#",$s,$m)){list(,$a,$b)=$m;$i=[42=>$a*$b,$a+$b,0,$a-$b,0,$a/$b,94=>$a**$b][ord($p)];}for(;$i;)$s+=array_sum(str_split($i--));echo$s;

60-0 bytes

<?for($i=$argv[1];$i;)$s+=array_sum(str_split($i--));echo$s;

260-25-50-10-100=75 bytes *

<?for($i=$argv[1];$p='^*/+-'[$k++];)while(preg_match("#(\d+)\\$p(\d+)#",$s,$m)){list(,$a,$b)=$m;$i=[42=>bcmul($a,$b),bcadd($a+$b),0,bcsub($a-$b),0,bcdiv($a,$b),94=>bcpow($a,$b)][ord($p)];}for(;$i;$i=bcsub($i,1))foreach(str_split($i)as$d)$s=bcadd($s,$d);echo$s;

x-25-50-10: yet to come ... find a golfable way to translate concatenated apbs to nested p(a,b)s. Or ... does preg_replace_callback qualify as eval?

* with PHP<5.3, you can use ereg("([0-9]+)\\$p([0-9]+)",$s,$m) instead of preg_match("#(\d+)\\$p(\d+)#",$s,$m) (-2 bytes)

breakdown for the last version

for($i=$argv[1];        # take string from argument 1
    $p='^*/+-'[$k++];)  # loop $p through operators in descending precedence
    # while operator (with two operands) is found in string ...
    while(preg_match("#(\d+)\\$p(\d+)#",$s,$m))
    {
        # get operators to $a and $b
        list(,$a,$b)=$m;
        # create an array of all operation results (key=ascii code of operator)
        # (may throw division by zero warnings)
        $i=[42=>bcmul($a,$b),bcadd($a+$b),0,bcsub($a-$b),0,bcdiv($a,$b),94=>bcpow($a,$b)]
        # and take the one matching the current operation
        [ord($p)];
    }
for(;$i;$i=bcsub($i,1))         # loop $i down to 1
    foreach(str_split($i)as$d)  # loop $d through digits
        $s=bcadd($s,$d);        # sum up
echo$s;                         # and print sum

Titus

Posted 2014-01-15T17:39:59.620

Reputation: 13 814

0

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

sergiol

Posted 2014-01-15T17:39:59.620

Reputation: 3 055

0

Add++, 14 bytes

D,f,@,RbUBDBFs

Try it online!

caird coinheringaahing

Posted 2014-01-15T17:39:59.620

Reputation: 13 702

0

Japt, 5 bytes

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

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

õì xx

Try it

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

OvU õì xx

Try it


Explanation

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

Shaggy

Posted 2014-01-15T17:39:59.620

Reputation: 24 623

0

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

IEatBagels

Posted 2014-01-15T17:39:59.620

Reputation: 189

0

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.

FlexEast

Posted 2014-01-15T17:39:59.620

Reputation: 31

The sequence of numbers should be generated by your code, not expected to find them all in the stack. – manatwork – 2018-07-10T15:38:44.613

Uhm… The problem is not related to site rules but the challenge: your code should take one integer, expand it the all numbers between 1 and the input then sum up their digits. Your code simply skips half of task. – manatwork – 2018-07-10T16:16:44.397

@manatwork ...I'm an idiot, completely missed half the problem. Thanks! – FlexEast – 2018-07-10T16:40:35.107

0

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.

mazzy

Posted 2014-01-15T17:39:59.620

Reputation: 4 832

0

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

RedClover

Posted 2014-01-15T17:39:59.620

Reputation: 719

Output is incorrect for n > 10, you need to split numbers into digits, and sum them. – u_ndefined – 2018-10-12T12:50:03.057

0

Kotlin, 38 bytes

No bonuses. (Int) -> Int lambda.

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

Try it online!

snail_

Posted 2014-01-15T17:39:59.620

Reputation: 1 982

0

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.

Kevin Cruijssen

Posted 2014-01-15T17:39:59.620

Reputation: 67 575

0

Squeak Smalltalk, fast version 111 octets - 25 bonus: 86

In class String, define method:

d|h s t|h:=self first:1.(s:=self size-1)>0or:[^h+1*h/2].t:=self last:s.^s*9+h-1*(5 raisedTo:s)<<(s-1)+t+1*h+t d

usage '1234567891234567891234564789087414984894900000000' d -> 265889343871444899381999757086453238874482500000214

This works because '1'+1 -> 2 dirtyness pay :)

The slow version 53 chars - 25 bonus: 18

In Integer, implement

d self=0or:[^('',self detectSum:[:d|'',d])+(self-1)d]

usage 12 d -> 51

It works for arbitrary long ints, but be patient...

It works because

  • '',12 -> '12' a String... dirty Squeakism :)
  • '',$1 -> '1' a String... dirty Squeakism :)
  • '1'+'2' -> 3 an Integer... dirty Squeakism :)
  • the method returns self by default (so 0)

A shame that detectSum: consumes so many chars, what a name!

The interpreter also works, but native integer division is //, not /, precedence of all binary operator is equal and expression is evaluated left to right, and unary message precedence requires (), so I did not count the 50 bonus...

(55*96-12)d -> 81393

How would cost an evaluator?
With unconventional precedence rules for * and /: 5*3/2*4 -> (5*(3/2))*4 rather than ((5*3)/2)*4 it is possible to make it in 118 chars - 150 bonus: -32

Define these two methods in String:

e:o o ifNotEmpty:[^((self findTokens:o first)collect:[:x|x e:o allButFirst])reduce:o first]

d^(0+(self e:#(+ - * //)))d

The string is split recursively against a list of operators o, around +, then - in inner loop, then *, then /

  • findTokens: performs the split on first operator '1+22+3' findTokens:#+ -> #('1' '22' '3')
  • collect: applies the recursion on remaining operators (allButFirst)
  • reduce: performs the operations (left to right)= #('1' '22' '3') reduce:#+ -> (1+22)+3->26

Given than selectors like allButFirst are rather long, manually nesting blocks and using splitBy: cost less 107 chars - 150 bonus: -43

f:o c:b^((self splitBy:o)collect:b)reduce:o

d^(self f:#+c:[:a|a f:#-c:[:b|b f:#*c:[:c|c f:#//c:[:d|d+0]]]])d

Reusing above Integer>>d, the total is 18-43 = -25

Usage is '55*96-12'd -> 81393

Note that it's not a program that takes a user input, but arguably in Squeak there is no such thing as a program, and user input happens everywhere, for example in any text pane of any window. You just press the 'do it' menu rather than press enter key...

previous slow version 58 chars - 25 bonus: 23

d self=0or:[^(#[],('',self)detectSum:[:d|d-48])+(self-1)d]

It works because

  • #[],'12' -> #[49 50] a ByteArray... dirty Squeakism :)

aka.nice

Posted 2014-01-15T17:39:59.620

Reputation: 411

0

Clojure, 104

(println (reduce (fn [a x] (+ a (apply + (map #(- (long %) 48) (seq (str x)))))) (range (inc (read)))))

Reads input on stdin and prints result to stdout.

To run, save to file sum.clj and call from shell (after installing Clojure):

echo 1000000 | java -jar clojure-1.5.1/clojure-1.5.1.jar sum.clj
27000001

You could also just paste the code into a lein repl (http://leiningen.org/) or run with lein exec plugin with echo 12 | lein exec sum.clj.

*Still waiting for results of 1234567891234567891234564789087414984894900000000 input for bonus points.

ctrlrsf

Posted 2014-01-15T17:39:59.620

Reputation: 1

How would you call it? – osvein – 2014-01-16T06:45:38.943

Edit has shorter code and running instructions. – ctrlrsf – 2014-01-16T14:28:49.850

0

Ruby, 124 - (100 + 50 + 25) = -51

e=->((a,b,*c)){x=a.to_i;b ?x.send(b,e[c]):x}
p (1..e[gets.split /\s|\b/]).lazy.flat_map{|x|x.to_s.chars.map &:to_i}.reduce:+

Some tests:

$ ruby count.rb <<<12
51
$ ruby count.rb <<<1000000
27000001
$ ruby count.rb <<<'6 + 3 * 8/4'
51

Explanation:

e is a function that evaluates an expression given an array of numeric strings and operators:

e[%w(3 + 2 * 2)] # => 7

All operators have the same precedence and are right-associative.

e works by taking the first two tokens, a and b, from the array and sending b as a message to a (which i assume is not in the same level of magic as eval, as sending messages is all we can do in Ruby after all) passing the evaluation of the rest of the array as the parameter.

The rest of the code should be more straightforward.

\s is used to split the line read from stdin to allow spaces between operators and numbers, and to get rid of the pesky newline at the end of the string.

The lazy call allows flat_map to return a lazy enumerator, which is then lazily consumed by reduce, instead of creating a ginormous intermediate array, thus making it possible to handle very big numbers without exhausting the memory and making me feel like it deserves the 25 point bonus :) ... even though computing the result for 2^64 would take eons with this method:

$ time ruby count.rb <<<100_000_000
3600000001

real    6m40.998s
user    6m41.272s
sys 0m0.020s

If the slowness makes this solution non eligible for the 25 point bonus, then i propose an eval-less version of @Chron's "older" answer:

105 - (100 + 50) = -45

e=->((a,b,*c)){x=a.to_i;b ?x.send(b,e[c]):x}
p"#{[*1..e[gets.split /\s|\b/]]}".chars.map(&:to_i).inject:+

epidemian

Posted 2014-01-15T17:39:59.620

Reputation: 531

@ST3 :( why not? – epidemian – 2014-02-03T12:45:23.273

Sorry, have fast run through all posts, I'm not into ruby very well, now added this as a request for revision. Maybe you are winner. – ST3 – 2014-02-03T13:13:45.603

@ST3, thanks. The code uses send to dynamically call methods on the numbers. It's not like eval in the sense that it doesn't need to parse code, or dynamically generate it. If you know JavaScript, it is analogous to using anObject[someMethodName](param1, param2) to call a method. If more clarification is needed, please let me know :)

– epidemian – 2014-02-03T13:21:04.037

0

Ruby :(69 - 25 - 30) = 14

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

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

aherve

Posted 2014-01-15T17:39:59.620

Reputation: 181

0

Gawk (115 - 50) = 65

{ "echo $(("$1"))"|getline x
  for(i=1;i<=x;i++){
   l=split(i,a,"")
   for(n=1;n<=l;n++) s+=a[n]
  } print s 
}

Requires GNU awk and a POSIX shell. Save the program as sum.awk and run it from the command line as:

% echo 55*96-12 | gawk -f sum.awk
81393
% echo 1000000 | gawk -f sum.awk
27000001

juniorzoid

Posted 2014-01-15T17:39:59.620

Reputation: 1

This should likely be listed as GAWK+SH – Robert Benson – 2018-01-15T15:02:51.547

0

Python (brute force solution)

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

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

Python (a more elegant solution)

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

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

GeneralBecos

Posted 2014-01-15T17:39:59.620

Reputation: 101

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

0

In Scala, something like this. Replace 12 with desired number

(1 to 12).flatMap( x=>x.toString().map(c=>(c.toInt - '0'.toInt))).foldLeft(0)(_+_)

kali sharma

Posted 2014-01-15T17:39:59.620

Reputation: 1

0

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

      +/,(16⍴10)⊤⍳

Examples:

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

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

user14894

Posted 2014-01-15T17:39:59.620

Reputation: 1

0

Haskell, 58-25 = 33

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

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

par.seq

Posted 2014-01-15T17:39:59.620

Reputation: 1

0

Javascript (82 - 50) = 32

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

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

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

scribblemaniac

Posted 2014-01-15T17:39:59.620

Reputation: 151

0

VB.net

Module z

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

End Module

Adam Speight

Posted 2014-01-15T17:39:59.620

Reputation: 1 234

0

Haskell 49 (74 - 25)

main=interact$show.sum.map fromEnum.foldr(++)"".map show.enumFromTo 1.read

Handles all positive numbers (barring if the sum of digits exceed maxBound :: Int.) Does not handle expressions of any kind.

Usage: echo $NUMBER | this-program

Karl Damgaard Asmussen

Posted 2014-01-15T17:39:59.620

Reputation: 129

0

Ruby 33 = 93 - 50 - 10

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

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

Karl Damgaard Asmussen

Posted 2014-01-15T17:39:59.620

Reputation: 129

0

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

import Data.Char
w=fromIntegral
q=w.digitToInt
e=sum
a(x:[])=e[1..q x]
a(x:y)=let p=w.length$y;f=q x in 45*10^(p-1)*p*f+10^p*e[1..f-1]+f*read y+f+a y

Counted bytes:

> wc -m solution.hs
150 solution.hs

I added 6 bytes for the call:

> a.show$ ...

-25:

> a.show$1234567891234567891234564789087414984894900000000
265889343871444899381999757086453238874482500000214

-50:

> a.show$55*96-12
81393

-10:

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

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

duedl0r

Posted 2014-01-15T17:39:59.620

Reputation: 101

0

PHP 5.3.6 112: 112

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

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

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

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

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

A little faster now, but longer.

Toby Allen

Posted 2014-01-15T17:39:59.620

Reputation: 101

0

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;

Shubanker

Posted 2014-01-15T17:39:59.620

Reputation: 101

0

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.

bela

Posted 2014-01-15T17:39:59.620

Reputation: 81

0

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)\\
% 

Aaron Davies

Posted 2014-01-15T17:39:59.620

Reputation: 881

Well if it uses % then you do not get 50 bonus, however you can slightly increase code size and get bonus. – ST3 – 2014-01-23T09:03:33.983

0

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
$ 

Digital Trauma

Posted 2014-01-15T17:39:59.620

Reputation: 64 644

0

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)        
        }
    }

Suppi

Posted 2014-01-15T17:39:59.620

Reputation: 1

0

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)

ThinkRedstone

Posted 2014-01-15T17:39:59.620

Reputation: 1

Haskell not Haskel :) – cat – 2016-06-30T23:30:46.950

0

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

Hans

Posted 2014-01-15T17:39:59.620

Reputation: 111

0

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

george

Posted 2014-01-15T17:39:59.620

Reputation: 1 495

Hi, welcome to the site! I'm counting 106 bytes, not 95. Are you sure you counted it right? Also, you could make it little bit shorter by doing x=1;exec"for z in str(x):a.append(int(z));x+=1;"*eval(input()) on line 2.

– James – 2016-06-13T16:10:56.080

@DrGreenEggsandIronMan thanks for the tip! Sorry I didn't realise you should include the spaces – george – 2016-06-13T16:54:54.470

0

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')`)

Patrick Roberts

Posted 2014-01-15T17:39:59.620

Reputation: 2 475

0

Factor, 44

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

cat

Posted 2014-01-15T17:39:59.620

Reputation: 4 989

0

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

m654

Posted 2014-01-15T17:39:59.620

Reputation: 765

0

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.

supermeerkat

Posted 2014-01-15T17:39:59.620

Reputation: 113

0

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

applejacks01

Posted 2014-01-15T17:39:59.620

Reputation: 989

0

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.

user902383

Posted 2014-01-15T17:39:59.620

Reputation: 1 360

0

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);}

o79y

Posted 2014-01-15T17:39:59.620

Reputation: 509

-1

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

microbian

Posted 2014-01-15T17:39:59.620

Reputation: 2 297

I'm pretty sure this can be trimmed a lot more. Also, if I'm not mistaken, it can't properly handle inputs greater than 2^63-1 because PowerShell defaults its integer types to signed. – Iszi – 2014-01-16T07:13:05.243

Here's an optimization with a base score (no bonuses/penalties evaluated) of 90. NOTE: This is only a golfing of your existing code - any bugs or limitations inherent in this answer will still be present here. for($n=read-host|iex;$n-gt0;$n--){$n.tostring().tochararray()|%{[double]$s+=[int]$_-48}}$s – Iszi – 2014-01-16T08:00:36.973

Correction: The script can probably deal with inputs of any size just fine. It will run into issues with any values for $s which are larger than (2^63)-1 though. And there's still a good load of optimization to be done even on the script I gave in the above comment. So much so that I just posted a separate answer which undercuts your original score by nearly 80 points. I strongly recommend you read the "Tips for golfing" threads around here, and check out other PowerShell answers, before trying to compete in the future. – Iszi – 2014-01-16T08:58:24.383

I know I could do optimizations. And your answer is excellent. Generally I don't answer to compete/win, that's why I don't try to golf too much. Anyways, why a downvote? – microbian – 2014-01-16T15:32:32.617

The down-vote isn't so much for being unnecessarily long (though that was a fair part of it - code-golf answers are generally expected to show at least some effort put into reducing the code size) as it is for not meeting the spec. By forcing $s to a double, your script will be incapable of properly handling any numbers which sum up larger than (2^63)-1. Since the challenge requires that you be able to process inputs up to (2^64)-1, that renders this answer invalid. – Iszi – 2014-01-16T15:39:44.437

Another problem with this one is that PowerShell doesn't naturally do integer division. So, this script cannot properly evaluate expressions per the requirements stated for the -50 bonus. My script also had the same weakness, and I just trimmed the iex bit out instead of bothering to fix it. I expect the code needed to properly implement integer division for this task will probably outweigh the bonus. – Iszi – 2014-01-16T18:17:56.603

-1

Python, 20 chars

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

flonk

Posted 2014-01-15T17:39:59.620

Reputation: 242

2Check your reading skills. First of all, this cannot be a function. Second, this is just wrong, as it sums numbers (which is something completely different). Read the description before putting a solution. – Konrad Borowski – 2014-01-16T12:37:22.880

@xfix oh thanks for your comment, I will check my reading skills! – flonk – 2014-01-16T13:22:23.283