title: Count sum of all digits

text:
# Question
Title: Count sum of all digits
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
# 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.
> 9 votes

# 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
> 14 votes

# 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`.
> 12 votes

# 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

```
> 11 votes

# Answer
## 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

```
> 8 votes

# 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*).
> 8 votes

# 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...
> 8 votes

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

```
> 6 votes

# Answer
# Scala 66

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

```
> 6 votes

# Answer
# Husk, 4 bytes

```
Σṁdḣ

```

Try it online!

* makes a range from 1 to input
* `ṁd` flatmap digits
* `Σ` sum
> 6 votes

# 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.
> 5 votes

# Answer
## 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!
> 4 votes

# 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.
> 4 votes

# 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). 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?
> 4 votes

# 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

```
> 3 votes

# 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.
> 3 votes

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

```
> 3 votes

# Answer
# 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).
> 3 votes

# Answer
# Vyxal, 3 - 160 = -157 bytes

```
ɾṅ∑

```

Try it Online!

Gaming. Use `**` for pow. This works because all input is auto evaluated
> 3 votes

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

```
> 2 votes

# 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.
> 2 votes

# 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.
> 2 votes

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

```
> 2 votes

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

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

# Answer
# 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

```
> 2 votes

# Answer
# Jelly, 5 - 160 = -155 bytes

```
ƓRDFS

```

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. Exponents must be with `**` instead of `^`
> 2 votes

# Answer
# Pyth, 6 bytes

```
ssMjkS

```

Try it online!

* `S` create range from 1 to input
* `jk` join on `k` (initially empty string)
* `sM` map to number
* `s` sum
> 2 votes

# 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, which has a numeric mode, but I haven't yet implemented this output method in it.

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

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

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

```

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

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

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

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

```

Try it online!
> 2 votes

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

```
> 1 votes

# Answer
**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;
}

```
> 1 votes

# 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

```
> 1 votes

# Answer
# 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]

```
> 1 votes

# Answer
# 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.
> 1 votes

# Answer
# Haskell, 74-25=49

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

# Answer
# 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('+')));alert(t);

```

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

# Answer
## ECMAScript 6, 86 - 50 = 36

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

```
> 1 votes

# Answer
# 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.
> 1 votes

# Answer
## 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

```
> 1 votes

# Answer
**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));}
}

```
> 1 votes

# Answer
# K, 16 - 50 = -34

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

```
> 1 votes

# Answer
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.
> 1 votes

# Answer
# 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

```
> 1 votes

# Answer
# 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()))

```
> 1 votes

# Answer
# 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.
> 1 votes

# Answer
# 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.
> 1 votes

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

```
hmss

```

Try it here!
> 1 votes

# Answer
## 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 :)
> 1 votes

# Answer
# 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)))))))

```
> 1 votes

# Answer
# 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 `apb`s 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

```
> 1 votes

# Answer
# 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 `BigInt`s 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[])))))

```
> 1 votes

# Answer
# Kotlin,  ~~38~~  36 bytes

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

```

Try it online!
> 1 votes

# Answer
# 05AB1E, score: -55 (~~11~~ 5 bytes -50-10 bonuses)

```
.ELSO

```

Inefficient, but it works.

Uses `**` instead of `^`.

Try it online.

Could be `.VLSO` if we take the input in Reverse Polish notation that 05AB1E uses, with `m` instead of `^`:

Try it online.

**Explanation:**

```
.E     # Python-eval the (implicit) input
       #  i.e. "55*96-2**6+156/3" → 5268.0
       # OR
.V     # 05AB1E-eval the (implicit) input
       #  i.e. "55 96*2 6m-156 3/+" → 5268.0
  L    # Pop and push a list in the range [1,n]
       #  → [1,2,3,....,5266,5267,5268]
   S   # Convert it to a flattened list of digits
       #  → [1,2,3,...,5,2,6,6,5,2,6,7,5,2,6,8]
    O  # Sum
       #  → 81393
       # (after which the result is output implicitly)

```

Would be **3 bytes** without any bonuses:

```
LSO

```

Try it online.
> 1 votes

# Answer
# Ly, 10 - 50 = -40 bytes

```
ns[Sl,s]&+

```

Try it online!

I'm assuming that since Ly is writen in Python, it can handle arbitrarily large numbers. If that's wrong, then it's 10 bytes. Here's how it works:

```
ns         - read the ending number from STDIN, save to backup cell
  [    ]   - loop until the top of stack is 0
   S       - convert the top of stack codepoint to digits, push them
    l,s    - load the backup cell, decrement and re-save
        &+ - sum the entries on the stack, automatically prints as integer

```
> 1 votes

# Answer
# Braingolf v2, 11 bytes

```
[.M1-]v&d&+

```

Try it online!

Doesn't work in v1 because the greedy `&` modifier is broken for `d`. Which is a shame because v1 is built on python and so supports arbitrarily large integers. v2 is built on JS and so uses doubles for everything.

## Explanation

```
[.M1-]v&d&+ ; Implicit input to stack
[....]      ; While loop, loop while top of stack != 0
 .M         ; Duplicate top of stack and move it to next stack
   1-       ; Decrement top of stack
      v     ; Switch to next stack
       &    ; Greedy - apply next function to entire stack
        d   ; Split into digits
         &  ; Greedy - apply next function to entire stack
          + ; Sum
            ; Implicit output of top of stack

```
> 1 votes

# Answer
# Vyxal, 8 bytes

```
ɾ(nf∑)W∑

```

Try it Online!
> 1 votes

# Answer
# Thunno 2 `S`, 2 - 160 = -158 bytes

Attempt This Online!

Just like the Vyxal answer, this qualifies for all the bounties. Uses `**` for `pow`.

#### Explanation

```
Rʂ  # Implicit input
R   # Push the range [1..n]
 ʂ  # Sum the digits of each number
    # S flag sums this list
    # Implicit output

```
> 1 votes

# Answer
**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 :)
> 0 votes

# Answer
**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.
> 0 votes

# Answer
# 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:+

```
> 0 votes

# Answer
**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.
> 0 votes

# Answer
### 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

```
> 0 votes

# Answer
### 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

```
> 0 votes

# Answer
# 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.
> 0 votes

# Answer
# Haskell, 58-25 = 33

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

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

```
> 0 votes

# Answer
# 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.
> 0 votes

# Answer
**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

```
> 0 votes

# Answer
## 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`
> 0 votes

# Answer
## 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.
> 0 votes

# Answer
## 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...
> 0 votes

# Answer
**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.
> 0 votes

# Answer
**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;

```
> 0 votes

# Answer
**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.

```
> 0 votes

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

```
> 0 votes

# Answer
# 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
$

```
> 0 votes

# Answer
**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)
        }
    }

```
> 0 votes

# Answer
# 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)
> 0 votes

# Answer
# 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

```
> 0 votes

# Answer
**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
> 0 votes

# Answer
# 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')`)
```
> 0 votes

# Answer
# Factor, 44

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

```
> 0 votes

# Answer
## 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

```
> 0 votes

# Answer
**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.
> 0 votes

# Answer
## 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.
> 0 votes

# Answer
# 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.
> 0 votes

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

```
> 0 votes

# Answer
# 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
> 0 votes

# Answer
# Add++, 14 bytes

```
D,f,@,RbUBDBFs

```

Try it online!
> 0 votes

# Answer
# 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

```
> 0 votes

# Answer
### 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

```
> 0 votes

# Answer
**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.
> 0 votes

# Answer
# 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.
> 0 votes

# Answer
# 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

```
> 0 votes

# Answer
# Fig, \\$4\log\_{256}(96)\approx\\$ 3.292 bytes

```
Sefa

```

Try it online!

Not gonna factor in bonuses

```
Sefa
   a # Range [1, n]
 ef  # Digits of each
S     # Sum

```
> 0 votes

# Answer
# Go, 75 bytes

```
func f(n int)(s int){for j:=1;j<=n;j++{for k:=j;k>0;k/=10{s+=k%10}}
return}

```

Attempt This Online!
> 0 votes

# Answer
# J-uby, 25 bytes

Not going for bonus points.

```
:+|:flat_map+:digits|:sum

```

Attempt This Online!
> 0 votes

# Answer
**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

```
> -1 votes

---
Tags: code-golf, math
---