22
\$\begingroup\$

Given a digit x (between 0 to 9, inclusive) and a number n, calculate the sum of the first n terms of the following sequence:

\$x,10x+x,100x+10x+x,\dots\$

For example, if x is 6 and n is 2, then the result will be 6+66 meaning 72.

There can be trailing whitespace in the output but not leading whitespace.

\$\endgroup\$
3
  • \$\begingroup\$ Welcome to Code Golf! This challenge looks fairly clear, although I'd definitely recommend using the sandbox for future challenges. \$\endgroup\$ – Redwolf Programs May 17 at 4:09
  • 1
    \$\begingroup\$ Welcome to CGCC! I've cleaned up the formatting a bit. I'd also highly recommend using the Sandbox for all challenges; this is a good challenge, but it's good to use it anyway; even I still use it for almost all of mine! As a tip, I'd recommend allowing I/O in "any reasonable format"; we have a pretty well-defined policy on that which is usually good for most challenges where input-output formatting isn't that important. Finally, more test cases usually helps, just to add to clarity and to offer some cases for answerers to test with. \$\endgroup\$ – hyper-neutrino May 17 at 4:19
  • \$\begingroup\$ OK I will use sandbox from next Time \$\endgroup\$ – java_learner May 17 at 4:21

37 Answers 37

15
\$\begingroup\$

Python 2, 28 bytes

lambda x,n:(10**-~n/9-n)/9*x

Try it online!

-6 thanks to @Bubbler and @tsh

Aha the first answer I have used some math

How?

Let's call \$n^{th}\$ term as \$y\$

$$ S_n=x+(10x+x)+(100x+10x+x)+.....+y\\= x+(11x)+(111x)+.....+y\\=\frac{x}{9}(9+99+999+.....+y)\\=\frac{x}{9}((10-1)+(100-1)+(1000-1)+.....+y)\\=\frac{x}{9}((10+100+1000+.....+y)-(1+1+1+.....+1))\\=\frac{x}{9}((10^1+10^2+10^3+...+y)-n)\\=\frac{x}{9}(\frac{10(10^n-1)}{10 - 1}-n)\\=\frac{x}{9}(\frac{10(10^n-1)-9n}{9})\\=\frac{x(10(10^n-1)-9n)}{81} $$

And we get our magic formula!

\$\endgroup\$
5
  • 1
    \$\begingroup\$ 30 bytes using floored division (29 if you switch to Python 2) \$\endgroup\$ – Bubbler May 17 at 5:17
  • \$\begingroup\$ I'm not quite sure if (10**-~n/9-n)/9*x is correct \$\endgroup\$ – tsh May 17 at 5:31
  • \$\begingroup\$ @tsh any problem in the formula? \$\endgroup\$ – wasif May 17 at 5:33
  • \$\begingroup\$ I'm pretty sure tsh's formula works (and saves one more byte). \$\endgroup\$ – Bubbler May 17 at 5:46
  • \$\begingroup\$ @Wasif I mean maybe you can save one more bytes by using (10**-~n/9-n)/9*x \$\endgroup\$ – tsh May 17 at 6:43
11
\$\begingroup\$

Jelly, 3 bytes

RḌ×

Try it online!

RḌ×    Dyadic link; left arg = n, right arg = x
R      [1..n]
 Ḍ     Undecimal, which is the same as 1 + 11 + ... + (n copies of 1)
  ×    Multiply x

These are the "backports" of the same algorithm into J and APL:

J, 9 bytes

*10#.1+i.

Try it online!

1+ is needed because J does not have 1-based range built-in.

APL (Dyalog Unicode), 6 bytes

10⊥×∘⍳

Try it online!

-1 byte thanks to @ovs

Uses a slightly different algorithm for golfing purposes: multiply x to 1..n, and then evaluate as base 10. This version of the algorithm works in Jelly too: R×Ḍ. Try it online!

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

JavaScript (Node.js), 24 bytes

t=>g=n=>n&&t*n+10*g(n-1)

Try it online!

$$ f(n,x)=\sum_{i=1}^n 10^{n-i}\cdot i\cdot x $$ $$ f(n,x)=nx+10\cdot f(n-1,x) \\ f(0,x)=0 $$

For example, we have:

\$f(6,3)\\ =6+66+666\\ =6+(60+6)+(600+60+6)\\ =600×1+60×2+6×3\\ =((6×1)×10+6×2)×10+6×3\\ =10\cdot f(6,2)+6×3\$

\$\endgroup\$
8
\$\begingroup\$

Excel, 29 bytes

=SUM(--REPT(A1,SEQUENCE(A2)))

x is input in A1 and n is input in A2. The formula goes anywhere else in the same sheet.

SEQUENCE(A2) creates an array of all the values from 1 to n.
REPT(A1,~) creates an array of strings of x repeated an increasing number of times based on the array created from the previous step.
--REPT(~) turns those strings into numbers.
SUM(~) adds up those numbers.

Screenshot

\$\endgroup\$
8
\$\begingroup\$

Vyxal R, 3 2 bytes

I*

Try it Online!

Thanks to @AaronMiller for -1

3 bytes, -rs

ƛ⁰ẋ

Try it Online!

;)

Explained

ƛ⁰ẋ
ƛ       # For each number n in the range [1, N]:
 ⁰ẋ     #  return x repeated n times (`-r` makes elements take arguments in reverse order)
        # The `-s` flag sums the top of the stack before outputting

4 bytes, s flag

ɾ?vẋ

Try it Online!

5 bytes, flagless

ɾ?vẋ∑

Try it Online!

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

J, 11 8 bytes

1#.".\@$

Try it online!

Assuming I can take the digit as a string...

Taking 3 f '6' as an example:

  • $ - Duplicate:

    '666'
    
  • ".\ Evaluate each prefix:

    6 66 666
    
  • 1#. Sum

    738
    
\$\endgroup\$
5
\$\begingroup\$

MATLAB/Octave, 28 26 bytes

-2 bytes thanks to Giuseppe

@(x,n)(1:n)*.1.^(1-n:0)'*x

Try it online!
Anonymous function.

How it works
First of all, sum $$x + (10x + x) + (100x + 10x + x) + ... + (10^{n-1}x + 10^{n-2}x + ... 10x + x)$$ can be transformed to: $$ n\cdot x + 10(n-1)\cdot x + 100(n-2) \cdot x + ... +10^{n-2} \cdot 2 x + 10^{n-1} x $$ which is: $$ x \cdot \sum_{i=0}^{n-1}(n-i) 10^i = x \cdot \sum_{i=0}^{n-1}(n-i)\cdot{0.1^{-i}}$$ Having that established:

  • 1:n is vector containing elements (n-1), but in reverse order of indexing than above
  • 1-n:0 are just indexes of sum above but reversed and negates (so -(n-1), -(n-2), ..., -1, 0)
  • .1.^(1-n:0) is then vector containing elements 0.1^(-i) in reversed order of indexing

To get the sum straightforward we would multiply elements of vectors element by element and then sum them like so (whitespace added for readability):

sum(  (1:n)  .*   (.1.^(1-n:0))   )

However, knowing how matrix multiplication works we can just transpose second vector and by multiplying the matrices:

(1:n)  *  (.1.^(1-n:0))'

we will get exactly the same result. And at the end we just multiply everything by x.

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

PowerShell Core, 41 bytes

param($x,$n)iex "$(1..$n|%{"+";"$x"*$_})"

Try it online!

Explanations

iex "$(...)"          # Run as a command the result of the list below, joined using spaces
1..$n|%{"+";"$x"*$_}  # From 1 to n, build a list containing +,x,+,xx,+,xxx,+,xxxx,...
\$\endgroup\$
4
\$\begingroup\$

R, 34 32 bytes

function(d,n)sum(10^(1:n)-1)*d/9

Try it online!

$$ x + (10x + x) + (100x + 10x + x) + \ldots = \\ x + 11x + 111x + \ldots = \\ (9x + 99x + 999x + \ldots)/9 = \\ (9+99+999+\ldots)*x/9 = \\ ((10-1)+(100-1)+(1000-1)+\ldots)*x/9 = \\ \big[\sum_{i=1}^n(10^i-1)\big]*x/9 $$

-2 bytes thanks to @Giuseppe


Using @Wasif's formula:

R, 34 bytes

function(d,n)d*(10*(10^n-1)/9-n)/9

Try it online!


Straightforward approach with strings:

R, 43 39 bytes

function(d,n)sum(strtoi(strrep(d,1:n)))

Try it online!

-4 bytes thanks to @Giuseppe

\$\endgroup\$
3
  • 1
    \$\begingroup\$ 31 bytes porting elementiro's answer. \$\endgroup\$ – Giuseppe May 18 at 13:16
  • \$\begingroup\$ @Giuseppe - nice approach. Do you want to post it youself? \$\endgroup\$ – pajonk May 18 at 17:10
  • \$\begingroup\$ Sure, posted. \$\endgroup\$ – Giuseppe May 18 at 18:59
3
\$\begingroup\$

Jelly, 4 bytes

ẋḌƤS

Try it online!

Explanation

ẋ     repeat `x` `n` times
  Ƥ   for each prefix
 Ḍ    convert it from digits to a decimal number
   S  and sum
\$\endgroup\$
3
\$\begingroup\$

Husk, 3 bytes

*dḣ

Try it online!

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

R, 31 bytes

function(d,n)10^(1:n-1)%*%n:1*d

Try it online!

Ports elementiro's answer.

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

Raku, 28 17 bytes

* *(1 Xx^*+1).sum

Golfed by Jo King from 28 byte solution:

  • Positional arguments $^a, $^b replaced by whatever-stars
  • Xx cross metaoperator responsible for generating 1, 11, 111...

Original, 28 bytes

{$^a*(^$^b+1).map(1 x*).sum}

Explanation

  • $^a is x, $^b is n
  • ^$^b+1 is shorthand for 0..^$^b+1, equivalent to 1..$^b
  • .map(1 x*) generates 1, 11, 111...
  • .sum adds the n-long sequence: 1 for n=1, 12, 123, etc.

Alternative, 32 bytes

{[+] ($^b…1)Z*($^a,* *10…*)}

Explanation

  • Z* zip-multiplies two lists, based on the observation that
    • 1E0 appears n times
    • 1E1 appears n-1 times
    • 1E2 appears n-2 times, etc.
\$\endgroup\$
2
  • \$\begingroup\$ 17 bytes. \$\endgroup\$ – Jo King May 19 at 0:48
  • \$\begingroup\$ Nice trick there with the X operator! \$\endgroup\$ – Zaid May 19 at 1:47
2
\$\begingroup\$

Python 3, 43 bytes

lambda x,n:sum(int(x*-~i)for i in range(n))

Try it online!

Accepts x as a string and n as an integer. If that's not acceptable, just use lambda x,n:sum(int(`x`*-~i)for i in range(n)) in Python 2 for +2 (+5 with str(x) in Python 3).

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

AWK, 26 bytes

{for(;$2--;b+=a)a=a$1}$0=b

Try it online!

I had an alternate algorithm I thought might be interesting, but it the code was longer... So this is pretty much a direct translation of the steps in the challenge description.

{for(;$2--;    )     }

Fir every line of input, the code runs the loop the number of times given by the second input parameter, the n value.

                a=a$1

The body of the loop appends another copy of the first input parameter to the requested digit, meaning the x value.

           b+=a

At the end of each iteration, the accumulator variable b is incremented by the current value of the digits placeholder.

                      $0=b

Finally, once the processing is done, $0=b overwrites the input line to display the accumulator value.

The only "trick" here is relying on the way AWK will happily treat variables as both strings and integers. Meaning, you can append digits together and still do mathematical operations using the results.

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

Perl 5 -pal, 22 bytes

map$\+="@F"x$_,1..<>}{

Try it online!

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

Japt -x, 3 bytes

Takes input in reverse order.

õçV

Try it

õçV     :Implicit input of integers U=n & V=x
õ       :Range [1,U]
 çV     :  For each, repeat V that many times
        :Implicit output of sum of resulting array
\$\endgroup\$
2
\$\begingroup\$

Factor + math.unicode, 44 bytes

[ [1,b] [ 10^ 1 - swap 9 / * ] with map Σ ]

Try it online!

Using the first thing that came to mind, $$ f(x,n)=\sum_{i=1}^n \frac{x}{9}(10^{i} - 1) $$

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

GolfScript, 20 21 bytes

~:x;0\),(;{'1'*~x*+}%

Try It Online!

takes as input a string containing n and x, in that order

Explanation

~:x;0\),(;{'1'*~x*+}%
~                      // parse the input string given
 :x;                   // bind the top value to the x variable
    0\                 // place a zero at the bottom of the stack
      ),(;             // create a list of numbers [1..n]
          {            // begin code block
           '1'*~       // create and evaluate a string of '1's to get the numbers 1, 11, 111...
                x*+    // multiply by x and add to the total (the zero we added)
                   }%  // execute this over every value in the list
                       // implicitly print the stack 
\$\endgroup\$
2
  • \$\begingroup\$ You aren't allowed to "assume[] that n and x have been pushed to the stack, with x at the top", that makes the answer a snippet, whereas only programs and functions are allowed by default (and this challenge doesn't override the default) \$\endgroup\$ – pppery May 17 at 17:41
  • \$\begingroup\$ Fixed. Thank you. \$\endgroup\$ – Ross Long May 17 at 21:58
2
\$\begingroup\$

Python 3, Python 2, 28 bytes

lambda x,n:(10**n/.9-n)//9*x

Try it online! Try it online!

Unfortunately I cannot add comments so I'm reposting Wasif's solution with a small tweak so that it works in both python versions. While at it, also correct the math.

$$ S_n=x+(10x+x)+(100x+10x+x)+...+y\\= x+(11x)+(111x)+...+y\\=\frac{x}{9}(9+99+999+...+\frac{9y}{x})\\=\frac{x}{9}((10-1)+(100-1)+(1000-1)+...+(\frac{9y}{x}+1-1))\\=\frac{x}{9}((10+100+1000+...+(\frac{9y}{x}+1))-(1+1+1+...+1))\\=\frac{x}{9}((10^1+10^2+10^3+...+10^n)-n)\\=\frac{x}{9}(\frac{10^{n+1}-10}{9}-n)\\=\frac{x}{9}(\frac{10(10^n-1)-9n}{9})\\=\frac{x(10(10^n-1)-9n)}{81} $$

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

C (gcc), 45 43 bytes

Saved 2 bytes thanks to Olivier Grégoire!!!

t;s;f(x,n){for(s=t=0;n--;)s+=t=t*10+x;n=s;}

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ t;s;f(x,n){for(s=t=0;n--;)s+=t=t*10+x;n=s;} saves 2 bytes, similarly to my Java answer. \$\endgroup\$ – Olivier Grégoire May 18 at 15:08
  • \$\begingroup\$ @OlivierGrégoire Nice one - thanks! :D \$\endgroup\$ – Noodle9 May 18 at 16:08
2
\$\begingroup\$

C# (Visual C# Interactive Compiler), 83 bytes

(a,b)=>Enumerable.Range(1,b).Sum(x=>Enumerable.Range(0,x).Sum(y=>a*Math.Pow(10,y)))

Try it online!

39 bytes using @Wasif's formula

(a,b)=>a*(10*(Math.Pow(10,b)-1)-9*b)/81

Try it online!

28 bytes using @tsh's formula

(a,b)=>b>0?a*b+10*f(a,b-1):0

Try it online!

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

05AB1E, 3 bytes

L×O

Try it online!

L       -- list [1..input]
 ×      -- string multiply with input
  O     -- sum
\$\endgroup\$
2
  • \$\begingroup\$ TIO link seems to be taking only one argument...? \$\endgroup\$ – Bubbler May 17 at 4:31
  • \$\begingroup\$ @Bubbler i changed the link to have an example with distinct inputs \$\endgroup\$ – Grimmy May 17 at 4:32
1
\$\begingroup\$

Red, 47 bytes

func[x n][t: s: 0 loop n[t: t + s: s * 10 + x]]

Try it online!

Alternative, 55 bytes

func[x n][t: copy""s: 0 loop n[s: s + to 1 append t x]]

Try it online!

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

Desmos, 30 26 bytes

f(x,n)=x(10(10^n-1)-9n)/81

Try It On Desmos!

Try It On Desmos!(Prettified)

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

Haskell, 24 bytes

n#x=x*div(10*10^n-9*n)81

Try it online!

Uses Wasif's formula.

Haskell, also 24 bytes

0#x=0
n#x=n*x+10*(n-1)#x

Try it online!

A port of tsh's excellent recursive formula.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Looks like the recursive formula from tsh also comes out at 24: TIO \$\endgroup\$ – xnor May 17 at 8:13
1
\$\begingroup\$

Retina, 20 bytes

.+(.)
*$1
L$v`.+
*
_

Try it online! Link includes test cases. Takes n as the first input. Note: Struggles for large values of n (5 is just about doable). Explanation:

.+(.)
*$1

Generate n copies of x.

L$v`.+
*

Convert each suffix to unary.

_

Take the sum and convert to decimal.

\$\endgroup\$
1
  • \$\begingroup\$ A non-Unary version that can handle large values of n takes 33 bytes: Try it online! \$\endgroup\$ – Neil May 17 at 12:09
1
\$\begingroup\$

Pip, 8 bytes

$+YaX\,b

Try it online!

Explanation

          a & b are command-line args (implicit)
   aX     String-multiply the digit by each number in...
     \,b  inclusive range from 1 through the number of terms
  Y       Yank (to enforce desired precedence)
$+        Fold on addition
          Autoprint (implicit)
\$\endgroup\$
1
\$\begingroup\$

Java (JDK), 53 bytes

x->n->{int r=0,y=0;for(;n-->0;)r+=y=y*10+x;return r;}

Try it online!

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

Lua, 46 bytes

function f(x,n)return(10*10^n-10-9*n)/81*x end

Try it online!

-11 bytes thanks to @Delfad0r

\$\endgroup\$
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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