[Question]
  [
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.
  
[Answer]
# 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
> 
> 
> 
[Answer]
## 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`.
[Answer]
## 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
```
[Answer]
# Perl 6: 108 - (25 + 50 + 100) + 0 = -67 points
Golfed solution (Final line based off of [xfix's great solution](https://codegolf.stackexchange.com/a/18616/15012)):
```
$!=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](https://codegolf.stackexchange.com/a/18616/15012).
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.
[Answer]
## python, 55-(50+25+10) = -30
In-efficient yet shorter and also able to handle expressions.
**EDIT:** Thanks [Wolframh](https://codegolf.stackexchange.com/users/7971/wolframh) and [legoStormtroopr](https://codegolf.stackexchange.com/users/8777/lego-stormtroopr) 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
```
[Answer]
# 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 `sig`th 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...
[Answer]
## 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*).
[Answer]
# Scala 66
```
println((1 to readLine().toInt).flatMap(x=>(x+"").map(_-'0')).sum)
```
[Answer]
## 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);}
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 4 bytes
```
Œ£·πÅd·∏£
```
[Try it online!](https://tio.run/##yygtzv7//9zihzsbUx7uWPz//39DIwA "Husk ‚Äì Try It Online")
* `·∏£` makes a range from 1 to input
* `·πÅd` flatmap digits
* `Œ£` sum
[Answer]
## 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.
[Answer]
## 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.
[Answer]
# 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](http://doc.perl6.org/type/Str#comb)). 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?
[Answer]
## Perl 31 - No bonuses
```
map{s/./$%+=$&/ge}0..<>;print$%
```
Sample output:
```
perl -e 'map{s/./$%+=$&/ge}0..<>;print$%'
1000000
27000001
```
## [Perl 5](https://www.perl.org/) with `-p`, 50 - 28 bytes: -22
```
map$\+=$_,/./g for 1..eval}{
```
[Try it online!](https://tio.run/##K0gtyjH9/z83sUAlRttWJV5HX08/XSEtv0jBUE8vtSwxp7b6/39DI21jEy1TM13zf/kFJZn5ecX/dQsA "Perl 5 ‚Äì Try It Online")
[Answer]
**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
```
[Answer]
## 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)
```
[Answer]
**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.
[Answer]
# [Dyalog APL](http://dyalog.com), 9 ‚Äì 160\* = -151
```
+/‚çé¬®‚àä‚çï¬®‚ç≥‚éï
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKO94L@2/qPevkMrHnV0PeqdCqR7Nz/qmwqS@q8ABgVcplwwlqERgmkAZx5ab2ikbWl2eLqpKQA "APL (Dyalog Unicode) ‚Äì 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](https://codegolf.stackexchange.com/questions/18556/count-sum-of-all-digits?page=3&tab=oldest#comment36286_18556).
**-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).
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 3 - 160 = -157 bytes
```
…æ·πÖ‚àë
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%C9%BE%E1%B9%85%E2%88%91&inputs=55*96-12&header=&footer=)
Gaming. Use `**` for pow. This works because all input is auto evaluated
[Answer]
**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)
            );
    }
}
```
[Answer]
## 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.
[Answer]
# 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.
[Answer]
**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));
  }
}
```
[Answer]
# 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.](http://cjam.aditsu.net/)
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.
[Answer]
# Python 3 + [astor](https://pypi.python.org/pypi/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
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 - 160 = -155 bytes
```
∆ìRDFS
```
[Try it online!](https://tio.run/##y0rNyan8///Y5CAXt@D//01NtSzNdA2NAA "Jelly ‚Äì Try It Online")
`∆ì`et evaluated input, turn it into a `R`ange, get the `D`igits of each, `F`latten into a single list, then `S`um
Claims the same bonuses as the [APL answer](https://codegolf.stackexchange.com/a/83354/66833). Exponents must be with `**` instead of `^`
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 6 bytes
```
ssMjkS
```
[Try it online!](https://tio.run/##K6gsyfj/v7jYNys7@P9/QyMA "Pyth ‚Äì Try It Online")
* `S` create range from 1 to input
* `jk` join on `k` (initially empty string)
* `sM` map to number
* `s` sum
[Answer]
# Regex `üêá` (Perl / PCRE2), 32 bytes, score 7
```
(\4?+(?=(x*)(\2{9})(x*))\3)+\2x+
```
Takes its input in unary, as a string of `x` characters whose length represents the number. Returns its output as the number of ways the regex can match. (The rabbit emoji indicates this output method. It can yield outputs bigger than the input, and is really good at multiplying.)
The **-25** bonus applies because there is no inherent limit to the numbers a unary regex can take as input ‚Äì though in standard regex engines an amount of memory must be allocated in bytes equal to the number being input. This doesn't apply to [RegexMathEngine](https://github.com/Davidebyzero/RegexMathEngine/), which has a numeric mode, but I haven't yet implemented this output method in it.
[Try it online!](https://tio.run/##RU9BTsMwELz3FZZlVV6ctE6AA3Vcp1K5cuqNVFaJWsmSaYMTpCBjjjyAJ/KR4AQkLqud2dndmebo7O3w/IaIE8jbS32wiCxFhLLYbnabdZidLo6SVnJRrAV4ZE4RgW@cOXcIV2csAiqtbBtrOopTnLSvT20XV3SSZkkGx5dRpP5ZHnlYEQ1ivNXGjwdX2iIHX9rHbC9j5XsRZghNn80fQUwhJ0HsGANP6mgJUdzjnhiQH0uqVsQBVcozRuqEBxhztPP5ZHVyGmNkAv1aJ2aB0ffnF8ILUkfhexyFoPX9w1brgVY3ilElaX8FtMr9XYCxheoaWJX3bBh4mnP@Aw "Perl 5 ‚Äì Try It Online") - Perl v5.28.2 / [Attempt This Online!](https://ato.pxeger.com/run?1=RU-xTsMwEBVrN_7gZFmVDyetExigjptWKisTG6miErWSJdOWJJWCjBn5AFaWDuWjYORLcFIQy929d-_u3r0ftsvS7L9OTh-egJYSrNkUCwN0KD1UyWx6Ox273mpTMlopIZOxRAt65RHabanXNZBsTaSDiVHV1uiakZAE1e6-qv1IHoRREOHysRWl_6zwPI5ojrLdVfmLi3JikhjtxNxFc-WjmEvXA-gu61-C6kR1Al9xjpYW3hIw0pCGalQvQ5aOaIksTS3ntAiEw_aPqt_vrHZO_RuRhKN1qgcEvl_fgAxo4YXPvuVcnl_fzPL8Y1evwstPYNlFylmqWHOGLIvtlcO2xOwceRY3_Kjb_yURxkIcwQ8 "Perl ‚Äì Attempt This Online") - Perl v5.36+  
[Try it online!](https://tio.run/##hVXrTttIFP6fpzi4WpiJnW4Sdis2xkQsRAK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yTywUqGUqgX24sr_Mk5QRQ4p3bydjmocvQx-dJdQxGB-G40t_Mhy_uRidTIZnq-Ph-8lwdCb3-8on82086dANg_cKJKDJfb0b1NvI1UL3trLh4z4QzI-LbOnngRCs4KRAlo-uXr82AHUdbF3B7gQmcbXydt0bWLKFghGsKbiCcGq8dHbx7DmANpUmy6QO0u5StyYUsVz8r1DBwqook4zvFFRm46wANV0e1szFiZHipCa6kRPuaO5Rd8V4VR5U4R1MTyCyhCiBVfmx_rzrQJ6VeK1vcPJHpNluGqPy4V2ZW5TZ8-o87_e5PBzswAVbydvQpTgweGeDpWetNMfZrd5d867dnbk4bJaYCVI60LxrSscwQSVezrya_joJicdlDx55vOuCbSf1iFekfKCATkkjpDnlGBKmDqUVP2NifR_BP7__AfjTkuCVHiHoWM2a7iXZlE_ZpYhZ7yh0OsGGUH8bTuPalJG6W85p3KMO7O8bG3ue6brx-HLsjy7fnExOz-kTRUW_WnutJoYoKvbMBsNfnS3dzfTH-W0i3jHJ5fPY2Lx3NVZcMEY28W03tBZY72l9IupLnBnrga0jwZ8O_T_AX1867V6nozf_AQ "C++ (GCC) ‚Äì Attempt This Online") - PCRE2 v10.40+
Although Perl and PCRE2 (and Raku, though its syntax is different) are the only regex engines currently capable of counting the number of possible matches without their source code being patched, this regex itself only uses an **ECMAScript** level of functionality.
```
                 # No anchor. This will result in the regex being able to match
                 # starting at any position, ranging from the input number to 0,
                 # meaning tail will equal each of those values in turn. Each will
                 # count towards the total number of possible matches.
(
    \4?+         # If this is the first iteration, do nothing, because \4 is unset.
                 # Otherwise, tail -= \4.
    (?=          # Atomic lookahead. Match what is inside, but upon exiting it,
                 # jump back to the position we were at before entering it, and
                 # never backtrack back into the lookahead to try different
                 # matches.
        # \2 = floor(tail / 10); \3 = \2 * 9; \4 = tail % 10
        (x*)(\2{9})(x*)
    )
    \3           # tail = tail - \3 == \2 + \4; leave \4 to be subtracted at the
                 # beginning of the next iteration, so that when we exit this loop,
                 # the remainder \4 is readily accessible.
)+               # Iterate the above loop any number of times, minimum one. Every
                 # number of possible iterations will be tried, meaning that the
                 # loop can exit after any iteration count, meaning the matching
                 # done after the loop will be applied to each digit in turn, with
                 # each adding linearly to the number of possible matches.
\2               # tail = tail - \2 = \4
# Each time we reach this point, tail = one of the digits of the number
x+               # Add \4 to the number of possible matches. This, and the number
                 # of iterations the above loop can do, are the only choices
                 # available for making a complete match.
```
Merely calculating the sum of digits of the input number N (instead of the sum of all sums of digits of 1 to N) actually takes a regex 1 byte *longer*, with a `^` anchor inserted at the beginning: [Try it online!](https://tio.run/##hVXrTuNGFP6fpzh4VZiJnW0S2hWNMRELkUDahVU2qNsl1DL2OBmtM7bs8XJZ8bcP0Efsg5SeuSQxJFItcOZyzndu3zmOi6Izi@PnNwlLuWDw6WQ86ocnl6ej8OrifBL@fn46OYOD1hsu4qxOGBwWccn6b@dHrXgelRAW1zcQwNh5f3f37Xa//uPh4ctk/u5uTp7/JNNfhi4ZBuS@Tcm0/@O3J6qWdLpP3Wn/3n2mr5UcD9pFEBZuz29YrGTJxUyZXJ/xHE9ZtDjakDtqcSGhwKUMWVnmJYlzUUnQ7rYXrKqiGaPwo5LJYBCjBBwegj1WS33ORJL5UDJZlwJ6/tMGptrHecI8uM3zDPIgjbJKwWozFu66/@u7G78F@PAUiM5cOGMWI7RSxOAQk/qrk7Pj8UGb2ksPKv7I8pSsHP95edKQp5RqK@ohOQxNEHFeSxjAKlCqwnO0GmgPBuC8Cl4rOw5qOVPh0FU@0qyu5iaSVVJaT61aVHwmWAJZLmbmFYnqjpW@TtjiIYyjLEM3bOx2F95mefwN2rEH33OeQDuJZIS5U0lSSwgCIOqmTXfXGNRiu@6qMl1bmUXEBUEA7WBxjUTImCAF7fRugq5vQjDsgCIOHDIcOD6u3KAwPw4lwxP836F4XiPifj@UWFTUVfAzXGjoJhAXRS2Vug4MSwjtki33i0jG81DH0l6vDVrJqjqTnimBbzvu8/nXkT5J04rhJcaLIczk/IVAO//OYolathLYeUv7i4JnjFhSfP40GdMifhuH6CyhnsX4OhpfhpPR@OP5xfFkdLo8Hn2ZjC5O1X5X@2R/rSddumbwTokEtLlvdoN@W7lG6MFGNkLcR5KFaZkvwiKSkpWClMjyi6sPHyxAUwdbV7J7iUlcroJt9xaWbKBgBCsKLiG8Bi@9bTx7DWBMZXzBmyCdHvUbQgkr5P8KlSyuy4rnYqugNpvmJejp8rhiLk6MDGczMY3MhWe4R/0l43V5UEV0MT2RzDnRAsvyY/1Fz4Mir/Da3OCsT8heZ88aVY/oqdyizE7Q5PlgINThcAsuuFrehR7FgSG6aywza5U5we7M7lr03N6Nj8NmgZkglQd793vKMUxQhZc3QUN/lQQeCNWDh4Ho@eC6vBnxkpSPFNApZYTsTQWGhKlDac3PlDg/JfDPX38Dflo4XpkRgo41rJleUk35kl2amM2OQqc5NoT@W3Ma17aM1N9wzuAedmF319rYCWzXjceX4/Di8uPx5OSMvlDU9Gu013JiyLJmr2ww/Ops6K6nP85vG/GWSa6ep9b6va2x0pIxso5vs6GNwGpPmxPRXOLMWA1sEwl@Op67nf1ut/tvnGbRrHruZFqrc/Af "C++ (gcc) ‚Äì Try It Online")
This regex apparently exposes a bug in the obsolete regex engine PCRE1: [Try it online!](https://tio.run/##fVThTtswEP7fpzgyQe0mRQ2dpq1pqBhj2g8GU1WkTbSKguukFqkTOclaYPzdA@wR9yDrznEDYWyL2sQ53313993nsCzrxoxtXgjJknLOYZgxxfcXhy22CBUE2eUMfBhbb1er66t@@eXm5vNk8Wq1IBsyfTmyycgn6w4l04O7N/dUL@m0T@3pwdre0D9jLAc6mR9ktuu1HvPlxVykOmHTpISMn9pEilYeLp/7HbaELCDDZRFwpVJFWCrzAqoGOkue52HM6R3mGQwYOsBwCFurXlZ2LueJB4oXpZLgevetUuYilnwOSSpjcwtlvuLKq7ItbwIWJklaFkTzVb8EV0nKrqHDKNwZd9t@gO0hbBUbCknQoQV4ZZfYRMIlyWjXnfk9D0xBpjXImG@R0cDycGX7mXlYlIyO8b9D0V4iZP8gKCDVwRo/xkWF3QQSMisLHa44dBT3oMkRkpIVykQrnpdJYdaazSjKeeEANodVxsXC7KRfOStSddmfmVSI6oNhIl1mIuFIyz4LMDmhDnw6Hp8E784nR6en8M28XUzev3Zgz2Q2izpVjxpMEQHZUZzW/EXViCOCbaG3A5YGqmpUEGJJVTjszgewm08liq2BafJsgZsTw7IfZ2m2I8QjuslbzWhFYsyLREhOjIaEdAyf1EMftx5lVTOGyR6ChkUqSOVU04A8SNeBLM1x2@xEQs5Ju9ve1qUv6Woi0WfHb85vMJDaOPoLLtiVvw1YyACTP2KZ4ep0kq/M26V0bXfmof6XyAvJHWiv27owbCXHzZnfiH8gQvhSa2voS9cD2xbNjutJ3VLAonQS0p7KtqFmSx/TRONRE/pmwc/vPwCVaw4IVtdIabSkFVjria85I4o7cHZxeuoAVixQItVvK0IH@tR7Vo9BGfZgb69GREor7Z2Mx@fj4Oz849Hk@AN9EvlwbOqSrROtL@spPk9y/v@wbW/15yVKynzxjy4b3d@3zL3S9MCIUXGOvdCHr8j2fLbuN73uQa/3i0VJGOebbqLZ@g0 "C++ (gcc) ‚Äì Try It Online") - the results start being incorrect from 10 onward.
Calculating the product of the of digits N is also 33 bytes:
```
^((?=(x*)(\2{9}))\3x*x+(?=\2$))+$
```
[Try it online!](https://tio.run/##hVXrTuNGFP6fpzh4t2TGdrZxUFc0xiAKkUDahVU2qNsFahl7nIzWGVv2eAms@NsH6CP2QUqPZyaJIZFqgTNzLt@5H8dF0ZvG8fObhKVcMPh0Mh4NwpPL01F4dXE@CX8/P52cwX7nDRdxVicMDoq4ZIN3s8NOPItKCIvrWwhgbP12f//tbq/@4@Hhy2T2/n5Gnv8k5CggC5uSm8GPX58ovdlb2AsHiTeDt5Q6b5/payXLBbsIwsLx/JbFSpZcTBuTaxrPkcqi@eGG3GGHCwkFHmXIyjIvSZyLSoJy156zqoqmjMKPSibDYYwScHAAhtwcFZ2JJPOhZLIuBXj@0wZmc4/zhLlwl@cZ5EEaZVUDq8wYuO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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();
}
```
[Answer]
# 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
```
]