19
\$\begingroup\$

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.

\$\endgroup\$
3
  • \$\begingroup\$ 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. \$\endgroup\$
    – Sundar R
    Feb 23, 2022 at 10:26
  • 3
    \$\begingroup\$ @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. \$\endgroup\$
    – pajonk
    Feb 23, 2022 at 10:50
  • \$\begingroup\$ @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". \$\endgroup\$
    – Sundar R
    Feb 23, 2022 at 11:05

33 Answers 33

5
\$\begingroup\$

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.

\$\endgroup\$
4
  • \$\begingroup\$ Welcome to Code Golf, and nice answer! \$\endgroup\$ Feb 22, 2022 at 14:26
  • 1
    \$\begingroup\$ 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 :-) \$\endgroup\$
    – Giuseppe
    Feb 22, 2022 at 14:27
  • \$\begingroup\$ 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. \$\endgroup\$ Feb 22, 2022 at 14:38
  • 2
    \$\begingroup\$ 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! \$\endgroup\$
    – Giuseppe
    Feb 22, 2022 at 16:38
4
\$\begingroup\$

Wolfram Language (Mathematica), 42 bytes

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

Try it online!

-2 bytes from att

\$\endgroup\$
1
  • \$\begingroup\$ 42 bytes \$\endgroup\$
    – att
    Feb 22, 2022 at 17:45
4
\$\begingroup\$

Julia 1.0, 43 38 30 bytes

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

Try it online!

-5 dingledooper, -8 MarcMush

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

R, 39 bytes

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

Try it online!

\$\endgroup\$
3
\$\begingroup\$

05AB1E, 8 bytes

FNg°<N-O

Try it online or verify all test cases.

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)
\$\endgroup\$
2
\$\begingroup\$

Vyxal r, 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↵-‹;∑

Try it Online! Flagless 9 bytes

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
\$\endgroup\$
1
  • \$\begingroup\$ Try it Online! for 7 bytes flagless, and 6 bytes with s flag \$\endgroup\$
    – lyxal
    Mar 28, 2023 at 23:32
2
\$\begingroup\$

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
 
\$\endgroup\$
2
\$\begingroup\$

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!

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

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!

\$\endgroup\$
2
\$\begingroup\$

Zsh, 35 bytes

for ((x=$1;x--;s+=1e$#x+~x)):
<<<$s

Attempt This Online!

\$\endgroup\$
2
\$\begingroup\$

PowerShell, 57 49 bytes

-8 bytes thanks to @mazzy!

0.."$args"-gt0|%{$s-=$_---("1e"+"$_".length)}
+$s

Try it online!

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

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
\$\endgroup\$
2
\$\begingroup\$

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
\$\endgroup\$
2
  • 1
    \$\begingroup\$ 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...) \$\endgroup\$ Mar 30, 2023 at 14:14
  • 1
    \$\begingroup\$ @DominicvanEssen That actually saves 4 nibbles because 0 is no longer a special case. Thanks! \$\endgroup\$
    – xigoi
    Mar 30, 2023 at 16:02
1
\$\begingroup\$

Japt -mx, 8 bytes

+1 byte to work around a bug in Japt.

aÓApUs l

Try it

\$\endgroup\$
1
\$\begingroup\$

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!

\$\endgroup\$
1
\$\begingroup\$

Dyalog APL, 17 bytes

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

⎕IO←0.

Try it online!

\$\endgroup\$
1
\$\begingroup\$

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\$

\$\endgroup\$
1
\$\begingroup\$

MATL, 14 bytes

:q"10@Vn^q@-vs

Try it online!

\$\endgroup\$
1
  • 1
    \$\begingroup\$ You could replace vs by ]vs :-P \$\endgroup\$
    – Luis Mendo
    Feb 24, 2022 at 16:00
1
\$\begingroup\$

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!

\$\endgroup\$
2
  • \$\begingroup\$ how the heck do you use desmos? \$\endgroup\$
    – DialFrost
    Feb 23, 2022 at 6:49
  • \$\begingroup\$ @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. \$\endgroup\$
    – Aiden Chow
    Feb 23, 2022 at 6:57
1
\$\begingroup\$

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.
\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

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 
\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

JavaScript, 35 bytes

f=n=>n&&f(--n)+10**`${n}`.length+~n

Try it online!

\$\endgroup\$
0
\$\begingroup\$

J, 24 bytes

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

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Python 2, 42 bytes

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

Try it online!

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Remove ~~ to save two bytes. n is integer, so those two symbols are not needed \$\endgroup\$
    – ophact
    Feb 22, 2022 at 17:57
0
\$\begingroup\$

Ruby, 39 bytes

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

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Charcoal, 12 bytes

I↨¹EN⁻I×Lι9ι

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

    N           Input as a number
   E            Map over implicit range
          9     Literal string `9`
       ×        Repeated by
         ι      Current value
        L       Length (of string representation)
      I         Cast to integer
     ⁻          Subtract
           ι    Current value
 ↨¹             Take the sum
I               Cast to string
                Implicitly print

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

\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

Pari/GP, 30 bytes

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

Try it online!

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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