# Sum of the first n elements of the sequence of 9's complement

Let's consider the following sequence:

$$9,8,7,6,5,4,3,2,1,0,89,88,87,86,85,84,83,82,81,80,79,78,77,76,75,74,73,72,71...$$ This is the sequence of $$\9\$$'s complement of a number: that is, $$\ a(x) = 10^d - 1 - x \$$ where $$\ d \$$ is the number of digits in $$\ x \$$. (A061601 in the OEIS).Your task is to add the first $$\n\$$ elements.

### Input

A number $$\n∈[0,10000]\$$.

### Output

The sum of the first $$\n\$$ elements of the sequence.

### Test cases

0 -> 0
1 -> 9
10 -> 45
100 -> 4050
1000 -> 408600
10000 -> 40904100


Standard rules apply. The shortest code in bytes wins.

• Do the test cases make sense? (I guess that's why the 0 confusion in the answers.) 0 -> 0 works if you take 0 as a 0-digit number, and the formula is 10^d - 1 - x as stated. But 1 -> 9 only works if the formula is 10^d - x. I think the 0 case should just be removed, and the formula changed to be without the - 1. Feb 23, 2022 at 10:26
• @SundarR I presume the confusion may result from indexing the sequence from 0 and then taking sum of first elements. So taking sum of first 0 elements results in 0 and taking first element (of index 0) results in 9. Feb 23, 2022 at 10:50
• @pajonk Ahh thank you. That was a reading fail on my part, I assumed it was "sum up to n's complement" and didn't read where it clearly says "sum of first n elements". Feb 23, 2022 at 11:05

# R, 37 bytes

f=function(n)sum(10^nchar(1:n-1)-1:n)


Try it online!

note I left out the check for 0 as I do not think it is part of the sequence as refered to A061601 in the OEIS reference. Adding the check would result in the exact same answer of Giuseppe, which would surely be preferable including the correct answer including 0.

• Welcome to Code Golf, and nice answer! Feb 22, 2022 at 14:26
• This is solid. It doesn't appear that this works for n=0 so you do need to adjust for that. Also, anonymous functions are perfectly fine (as long as they're not recursive), so you can drop the f= from your answer as well :-) Feb 22, 2022 at 14:27
• We cross posted the same answer, I learned your *!!n part which is very elegant to include the n=0. I do think though if an OP asks for a oeis defined sequence, the offset value or in other words the value not part of that defined sequence should not be addressed in the answer. Feb 22, 2022 at 14:38
• That's up to the discretion of the question asker, I believe. You can ask in a comment on the main post if you want, though. Also, I recommend looking at the tips for golfing in R; they can be helpful sometimes! Feb 22, 2022 at 16:38

# Wolfram Language (Mathematica), 42 bytes

FromDigits[9-IntegerDigits@--n]~Sum~{n,#}&


Try it online!

-2 bytes from att

• 42 bytes
– att
Feb 22, 2022 at 17:45

# Julia 1.0, 4338 30 bytes

!n=n>0&&10^ndigits(~-n)-n+!~-n


Try it online!

-5 dingledooper, -8 MarcMush

• 38 bytes: !n=n>0&&sum(n->~n+10^ndigits(n),0:n-1) Feb 22, 2022 at 16:40
• 30 bytes with recursion: !n=n>0&&10^ndigits(~-n)-n+!~-n Feb 23, 2022 at 19:03

# R, 39 bytes

function(n)sum(10^nchar(1:n-1)-1:n)*!!n


Try it online!

# 05AB1E, 8 bytes

FNg°<N-O


Explanation:

F         # Loop N in the range [0, (implicit) input):
Ng       #  Push the length of N
°      #  Take 10 to the power this length
<     #  Decrease it by 1
N-   #  Decrease it by N
O  #  Take the sum of the values on the stack
# (after which the last sum is output implicitly as result -
# or the implicit input if it was 0 and we never entered the loop)


# Vyxalr, 8 bytes

No, I'm not Jo King. I found another use for the r flag!!!

It happens once in a blue moon on average

Okay, yes, I said that

ʁƛL↵-‹;∑


## Explanation

So the r flag is basically a reverser, which reverses the order of the arguments. That makes it hard to use for long programs, but for short ones like this, it's useful sometimes.

ʁƛL↵-‹;∑
ʁ          create list with range(0, n)
ƛ         open mapping lambda (with loop item n)
L↵       push 10 to the length of n
-      n - the latter (because it's reversed)
‹;    decrement by 1 and close lambda
∑   sum list

• Try it Online! for 7 bytes flagless, and 6 bytes with s flag Mar 28, 2023 at 23:32

# Jelly, 7 bytes

’æċ⁵_)S


A monadic Link accepting a non-negative integer that yields a non-negative integer.

Try it online!

### How?

’æċ⁵_)S - Link: non-negative integer, n
)  - for each i in [1..n] (if n is 0 this will yield []):
’       -   decrement -> i-1
⁵    -   10
æċ     -   ceil i-1 to the nearest (positive integer) power of 10
_   -   subtract i
S - sum



# Python 3.8 (pre-release), 50 44 bytes

Gave a fun recursive solution a go :)

edit: -6 bytes thanks to solid.py

f=lambda n:n and f(m:=n-1)-n+10**len(str(m))


Try it online!

• Welcome to Code Golf, and nice answer! Feb 22, 2022 at 15:45
• Actually, 44 bytes Feb 22, 2022 at 17:38
• @solid.py yes! haha, that one was painfully obvious Feb 22, 2022 at 17:46
• Surely repeating n-1 saves a byte, as the assignment takes three bytes.
– Neil
Feb 22, 2022 at 19:55

# C (gcc), 79 bytes

g(n,t,s){t=--n/10;s=n%10+1;n=t*45+s*(19-s)/2+10*(t?s*g(t+1)+(10-s)*g(t)-90:0);}


Try it online!

# Zsh, 35 bytes

for ((x=$1;x--;s+=1e$#x+~x)):
<<<$s Attempt This Online! # PowerShell, 57 49 bytes -8 bytes thanks to @mazzy! 0.."$args"-gt0|%{$s-=$_---("1e"+"$_".length)} +$s


Try it online!

• 1e2 = 100, 1e3 = 1000, 1e4 = 10000... Feb 22, 2022 at 19:59
• Feb 22, 2022 at 20:13
• @mazzy Ahhhhh, clever, thank you! I totally forgot about scientific notation in powershell!! And nice way to improve on the zero case Feb 24, 2022 at 12:56

# Behaviour, 36 29 bytes

f=&#(a*&10^#(""+a)-1-a;>&a+b)


My own recently made esolang, so bear with me.

ungolfed and commented

f=&
#(                  // deal with 0 case, convert nil into 0
a * &             // generate array for n nine complements
10^#(""+a)-1-a; // nine complements logic
>&a+b             // reduce array by adding its items
)


Test with:

f:0
f:1
f:10


# Nibbles, 8.5 6.5 bytes

+.,$-^~,p-$~


Attempt This Online!

-2 bytes thanks to Dominic van Essen

+.,$-^~,p-$~
+             Sum
.             for n in
,             range from 1 to
$input - subtract ^~ 10 to the power of , length of p convert to string - ~ subtract 1 from$        n
n

• Use "int to str" (backtick-p) instead of "to base" (backtick-@~) save 1 nibble... (no idea how to type the backticks directly into the comment...) Mar 30, 2023 at 14:14
• @DominicvanEssen That actually saves 4 nibbles because 0 is no longer a special case. Thanks! Mar 30, 2023 at 16:02

# Japt-mx, 8 bytes

+1 byte to work around a bug in Japt.

aÓApUs l


Try it

# Python 3, 49 bytes

-1 byte thanks to user friddo

lambda n:sum(~i+10**len(str(i))for i in range(n))


Try it online!

# Dyalog APL, 17 bytes

+/⍳-⍨1-⍨10*≢∘⍕¨∘⍳


⎕IO←0.

Try it online!

# JavaScript, 47 bytes

f=n=>(t=10**${n}.length)*n+n*~n/2+~-t*~t/11+9  Try it online! There isn't any non-recursive implementation here. So maybe it is worth to include one. But it is longer than current answers... If your language trunk divide result to int automatically, +~-t*~t/11 could be changed into -t*t/11. $$t = 10^{1+\lfloor\log_{10}n\rfloor}$$ $$t\cdot n-\frac{n\cdot (n+1)}2-\frac{t^2-100}{11}$$ with special case where $$\n=0\$$ # MATL, 14 bytes :q"10@Vn^q@-vs  Try it online! • You could replace vs by ]vs :-P Feb 24, 2022 at 16:00 # Desmos, 49 bytes f(k)=∑_{n=2}^k(10^{1+floor(log(n-1))}-n)+9-0^k9  Would be 44 bytes if we didn't have to deal with 0... Try It On Desmos! Try It On Desmos! - Prettified ## 48 bytes, port of @tsh's answer t=10^{log(n+0^n)}10 f(n)=tn-(nn+n)/2-(tt-100)/11  Try It On Desmos! • how the heck do you use desmos? Feb 23, 2022 at 6:49 • @DialFrost it's hard to explain fully in a comment, but the gist is that Desmos uses mathematical formulae (like functions or expressions) in order to compute the output. these formulae are expressed through $\LaTeX$ (albeit with certain optimizations for byte count), which is the code you see. Feb 23, 2022 at 6:57 # Raku, 32 bytes 0,|[\+] {{S:g/./9/-$_}($++)}...*  Try it online! This is an expression for the infinite sequence of sums. • { ... } ... * is a lazy, infinite sequence, where the brackets enclose an expression that generates each sequence element. • $++ postincrements an anonymous state variable each time the generating function is called, producing the numbers 0, 1, 2, .... Each time, that number is passed to the anonymous function enclosed in the inner brackets. (That saves us having to declare a variable to hold the counter value.)
• S:g/./9/ converts every digit in the counter to 9.
• - $_ subtracts the counter from the previous value. • [\+] produces the sequence of partial sums from the original sequence. • 0, | pastes a zero onto the front of the sequence. # J-uby, 32 bytes :*|:sum+(-[S|:+@|:**&10,:~]|+:+)  Attempt This Online! ## Explanation :* | :sum + ( -[ S | :+@ | :** & 10, :~ ] | +:+ ) :* | # 0...input :sum + ( ) # Sum by -[ , ] | +:+ # Sum of S | :+@ | :** & 10 # 10 to the power of the number of digits :~ # and two's complement  # Thunno, $$\ 11 \log_{256}(96)\approx \$$ 9.05 bytes eDL10@1-_ES  Attempt This Online! #### Explanation  # Implicit input e # Map over range(input): DL # Duplicate and push the length 10 # Push ten @ # Push 10 ** length 1- # Subtract one _ # Subtract the loop variable ES # After the map, sum # Implicit output  # FunStack alpha, 60 bytes Cons 9 Reverse From0 over flatmap Times 9 Pow 10 #N Sum Take  Try it at Replit! ### Explanation First, we construct the infinite list [9,8,7,6,5,4,3,2,1,0,89,88,87,...]: #N  Natural numbers starting from 0. Times 9 Pow 10  Take 10 to the power of each number, then multiply by 9. Reverse From0 over flatmap  Create a function that takes a number, generates the range from 0 to that number (exclusive), and reverses it. Then map that function to each number in the above list and flatten the resulting list of lists. (What we're doing here is really just function composition, but over is fewer bytes than compose and does the same thing in this case.) Cons 9  Stick a 9 on the front of the list. Now this value gets appended to the program's argument list (which previously contained the input number, N), and we apply the following functions: Take  Take the first N values from the infinite list. Sum  Sum them. # JavaScript, 35 bytes f=n=>n&&f(--n)+10**${n}.length+~n


Try it online!

# J, 24 bytes

+/@((10&^@#@":->:)"0@i.)


Try it online!

# Python 2, 42 bytes

f=lambda n:n and-~~n+10**len(n-1)+f(n-1)


Try it online!

• Remove ~~ to save two bytes. n is integer, so those two symbols are not needed Feb 22, 2022 at 17:57

# Ruby, 39 bytes

->n{n.times.sum{|x|10**x.to_s.size+~x}}


Try it online!

# Charcoal, 12 bytes

Ｉ↨¹ＥＮ⁻Ｉ×Ｌι9ι


Try it online! Link is to verbose version of code. Explanation:

    Ｎ           Input as a number
Ｅ            Map over implicit range
9     Literal string 9
×        Repeated by
ι      Current value
Ｌ       Length (of string representation)
Ｉ         Cast to integer
⁻          Subtract
ι    Current value
↨¹             Take the sum
Ｉ               Cast to string
Implicitly print


(Sum() won't work for an input of 0.)

# Burlesque, 19 bytes

-.{Jln'9j.*j|-}GZ++


Try it online!

-.   # Decrement (Burlesque runs 0..N inclusive, need to exclude)
{
J   # Duplicate
ln  # Number of digits
'9  # Character 9
j   # Reorder stack
.*  # Repeat 9 n_digits times as string
j   # Reorder stack
|-  # String subtract (parse and subtract)
}GZ  # Generate for range
++   # Sum


# Pari/GP, 30 bytes

n->sum(i=0,n-1,10^#Str(i)-1-i)
`

Try it online!