title: Compute the perimeter density matrix

text:
# Question
Title: Compute the perimeter density matrix
## Introduction

The *perimeter density matrix* is an infinite binary matrix **M** defined as follows. Consider a (1-based) index **(x, y)**, and denote by **M\[x, y\]** the rectangular sub-matrix spanned by the corner **(1, 1)** and **(x, y)**. Suppose that all values of **M\[x, y\]** except **Mx, y**, the value at index **(x, y)**, have already been determined. Then the value **Mx, y** is whichever of **0** or **1** that puts the average value of **M\[x, y\]** closer to **1 / (x + y)**. In case of a tie, choose **Mx, y = 1**.

This is the sub-matrix **M\[20, 20\]** with zeros replaced by dots for clarity:

```
1 . . . . . . . . . . . . . . . . . . .
. . . . . 1 . . . . . . . . . . . . . .
. . 1 . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . 1 . . . . . . . . . . . . . . .
. 1 . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . 1 . .
. . . . . . . . . . . . . . 1 . . . . .
. . . . . . . . . . . . 1 . . . . . . .
. . . . . . . . . . 1 . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . 1 . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . 1 . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . 1 . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .

```

For example, we have **M1, 1 = 1** at the upper left corner, since **1 / (1 + 1) = ½**, and the average of the **1 × 1** sub-matrix **M\[1, 1\]** is either **0** or **1**; that's a tie, so we choose **1**.

Consider then the position **(3, 4)**. We have **1 / (3 + 4) = 1/7**, and the average of the sub-matrix **M\[3, 4\]** is **1/6** if we choose **0**, and **3/12** if we choose **1**. The former is closer to **1/7**, so we choose **M3, 4 = 0**.

Here is the sub-matrix **M\[800, 800\]** as an image, showing some of its intricate structure.

## The task

Given a positive integer **N \< 1000**, output the **N × N** sub-matrix **M\[N, N\]**, in any reasonable format. The lowest byte count wins.

# Answer
> 3 votes
# R, 158 154 141 bytes

Edit: Because the only `1` in the upper `2x2` submatrix is the top left `M[1,1]` we can start the search for `1s` when `{x,y}>1` so no need for the `if` statement.

```
M=matrix(0,n<-scan(),n);M[1]=1;for(i in 2:n)for(j in 2:n){y=x=M[1:i,1:j];x[i,j]=0;y[i,j]=1;d=1/(i+j);M[i,j]=abs(d-mean(x))>=abs(d-mean(y))};M

```

The solution is highly inefficient as the matrix is duplicated twice for each iteration. `n=1000` took just under two and a half hours to run and produces a matrix of `7.6` Mb.

**Ungolfed and explained**

```
M=matrix(0,n<-scan(),n);                        # Read input from stdin and initialize matrix with 0s
M[1]=1;                                         # Set top left element to 1
for(i in 2:n){                                  # For each row
    for(j in 2:n){                              # For each column
        y=x=M[1:i,1:j];                         # Generate two copies of M with i rows and j columns
        x[i,j]=0;                               # Set bottom right element to 0
        y[i,j]=1;                               # Set bottom right element to 1
        d=1/(i+j);                              # Calculate inverse of sum of indices
        M[i,j]=abs(d-mean(x))>=abs(d-mean(y))   # Returns FALSE if mean(x) is closer to d and TRUE if mean(y) is
    }
};
M                                               # Print to stdout

```

Output for `n=20`

```
      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] [,15] [,16] [,17] [,18] [,19] [,20]
[1,]     1    0    0    0    0    0    0    0    0     0     0     0     0     0     0     0     0     0     0     0
[2,]     0    0    0    0    0    1    0    0    0     0     0     0     0     0     0     0     0     0     0     0
[3,]     0    0    1    0    0    0    0    0    0     0     0     0     0     0     0     0     0     0     0     0
[4,]     0    0    0    0    0    0    0    0    0     0     0     0     0     0     0     0     0     0     0     0
[5,]     0    0    0    0    1    0    0    0    0     0     0     0     0     0     0     0     0     0     0     0
[6,]     0    1    0    0    0    0    0    0    0     0     0     0     0     0     0     0     0     0     0     0
[7,]     0    0    0    0    0    0    0    0    0     0     0     0     0     0     0     0     0     0     0     0
[8,]     0    0    0    0    0    0    0    0    0     0     0     0     0     0     0     0     0     1     0     0
[9,]     0    0    0    0    0    0    0    0    0     0     0     0     0     0     1     0     0     0     0     0
[10,]    0    0    0    0    0    0    0    0    0     0     0     0     1     0     0     0     0     0     0     0
[11,]    0    0    0    0    0    0    0    0    0     0     1     0     0     0     0     0     0     0     0     0
[12,]    0    0    0    0    0    0    0    0    0     0     0     0     0     0     0     0     0     0     0     0
[13,]    0    0    0    0    0    0    0    0    0     1     0     0     0     0     0     0     0     0     0     0
[14,]    0    0    0    0    0    0    0    0    0     0     0     0     0     0     0     0     0     0     0     0
[15,]    0    0    0    0    0    0    0    0    1     0     0     0     0     0     0     0     0     0     0     0
[16,]    0    0    0    0    0    0    0    0    0     0     0     0     0     0     0     0     0     0     0     0
[17,]    0    0    0    0    0    0    0    0    0     0     0     0     0     0     0     0     0     0     0     0
[18,]    0    0    0    0    0    0    0    1    0     0     0     0     0     0     0     0     0     0     0     0
[19,]    0    0    0    0    0    0    0    0    0     0     0     0     0     0     0     0     0     0     0     0
[20,]    0    0    0    0    0    0    0    0    0     0     0     0     0     0     0     0     0     0     0     0

```

# Answer
> 3 votes
# Python, ~~129~~ ~~119~~ ~~117~~ 115 bytes

* Replaced the loop with a list comprehension so everything can go on one line and can be lambda
* Replaced .append() with :=z+\[\]
* -2 bytes thanks to @ceilingcat for pointing out that `(1+a)*(1+c) = (-a-1)*(-b-1)`
* -1 bytes thanks to @ceilingcat for removing the 0 from .5
* -1 byte thanks to @thonnu for a more efficinet way to do `and z` at the end.

```
lambda x,z=[]:[z:=z+[~(i//x)*~(i%x)/(i//x+i%x+2)>=sum(z[k]&(k%x<=i%x)for k in range(i))+.5]for i in range(x*x)][-1]

```

Attempt This Online!

Rust is no longer better than python. Port of my Rust answer. Outputs a flattened matrix

# Python, ~~118~~ 111 bytes

```
def f(x,z=[]):
 for i in range(x*x):z+=[~(i//x)*~(i%x)/(i//x+i%x+2)>=sum(z[k]&(k%x<=i%x)for k in range(i))+0.5]

```

Attempt This Online!

Thanks to @xnor and @ceilingcat. Outputs my modifying the input in place.

# Answer
> 3 votes
# BQN, 36 bytesSBCS

```
+`⁼{˘>(⊣-⌊`∘-)`<˘⌊0.5+(×÷+)⌜˜1+↕}

```

Run online!

Two observations:

* Minimizing distance of mean to `1/(x+y)` is the same as minimizing distance of sum to `x×y/(x+y)`.
* At least up to 1000×1000, which is maximum size required in the challenge, there is no row or column with two ones.

The function performs three major steps:

`⌊0.5+(×÷+)⌜˜1+↕` Generate matrix **round(x×y/(x+y))**.

`(⊣-⌊`∘-)`<˘` Calculate matrix **sum(M\[x, y\])**.

`+`⁼+`⁼˘` Convert that to the *perimeter density matrix* by performing *inverse cumulative sum* (`+`⁼`) on rows and columns.

This runs reasonably fast, generating the full 1000x1000 in ~60ms locally, but some less golfed version were a bit faster.

# Answer
> 2 votes
# Scala 3, ~~565~~ ~~476~~ ~~460~~ ~~458~~ ~~447~~ 440 bytes

Golfed version. Attempt this online!

Saved 125 bytes (565-\>440) thanks to the comment of @ceilingcat

```
@main def m={val n=scala.io.StdIn.readInt();val M=Array.ofDim[Int](n,n);M(0)(0)=1;for(i<-1 until n;j<-1 until n){val z=M.slice(0,i+1);val x=z.map(_.slice(0,j+1));val y=z.map(_.slice(0,j+1));x(i)(j)=0;y(i)(j)=1;val d=1.0/(i+j+2);M(i)(j)=if(a(x,d)<a(y,d))0 else 1};M.foreach(o=>{o.foreach(l=>print(if(l<1)"."else 1));println("")});def a(m:Array[Array[Int]],d:Double)=math.abs(d*m.length*m.headOption.map(_.length).getOrElse(0)-m.flatten.sum)}

```

---

Ungolfed version. Attempt this online!

```
import scala.io.StdIn.readInt

object Main extends App {
  val n = readInt()
  val M = Array.ofDim[Int](n, n)
  M(0)(0) = 1

  for (i <- 1 until n) {
    for (j <- 1 until n) {
      val x = M.slice(0, i + 1).map(_.slice(0, j + 1))
      val y = M.slice(0, i + 1).map(_.slice(0, j + 1))
      x(i)(j) = 0
      y(i)(j) = 1
      val d = 1.0 / (i + j + 2)

      M(i)(j) = if (math.abs(d - mean(x)) >= math.abs(d - mean(y))) 1 else 0
    }
  }

  for (row <- M) {
    for (ele <- row) {
      if (ele == 0) print(".") else print(1)
    }
    println("")
  }

  def mean(matrix: Array[Array[Int]]): Double = {
    val rowCount = matrix.length
    val colCount = matrix.headOption.map(_.length).getOrElse(0)
    matrix.flatten.sum.toDouble / (rowCount * colCount)
  }
}

```

# Answer
> 1 votes
# Python 2, 189 Bytes

There are no crazy tricks in here, it is just calculating as described in the introduction. It isn't particularly quick but I don't need to create any new matrices to do this.

```
n=input()
k=[n*[0]for x in range(n)]
for i in range(1,-~n):
 for j in range(1,-~n):p=1.*i*j;f=sum(sum(k[l][:j])for l in range(i));d=1./(i+j);k[i-1][j-1]=0**(abs(f/p-d)<abs(-~f/p-d))
print k

```

Explanation:

```
n=input()                                     # obtain size of matrix
k=[n*[0]for x in range(n)]                    # create the n x n 0-filled matrix
for i in range(1,-~n):                        # for every row:
  for j in range(1,-~n):                      # and every column:
    p=1.*i*j                                  # the number of elements 'converted' to float
    f=sum(sum(k[l][:j])for l in range(i))     # calculate the current sum of the submatrix
    d=1./(i+j)                                # calculate the goal average
    k[i-1][j-1]=0**(abs(f/p-d)<abs(-~f/p-d))  # decide whether cell should be 0 or 1
print k                                       # print the final matrix

```

For those curious, here are some timings:

```
 20 x  20 took 3 ms.
 50 x  50 took 47 ms.
100 x 100 took 506 ms.
250 x 250 took 15033 ms.
999 x 999 took 3382162 ms.

```

"Pretty" output for `n = 20`:

```
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

```

# Answer
> 1 votes
# Rust, 152 bytes

```
|z|{let mut b=vec![];for i in 0..z*z{b.push(((1+i/z)*(1+i%z))as f32/(i/z+i%z+2)as f32>=(0..i).map(|d|(d%z<=i%z&&b[d])as u8 as f32).sum::<f32>()+0.5)};b}

```

Attempt This Online!

Lots of wasted space due to needing `as f32` everywhere :(

# Answer
> 0 votes
## Racket 294 bytes

```
(define(g x y)(if(= 1 x y)1(let*((s(for*/sum((i(range 1(add1 x)))(j(range 1(add1 y)))#:unless(and(= i x)(= j y)))
(g i j)))(a(/ s(* x y)))(b(/(add1 s)(* x y)))(c(/ 1(+ x y))))(if(<(abs(- a c))(abs(- b c)))0 1))))
(for((i(range 1(add1 a))))(for((j(range 1(add1 b))))(print(g i j)))(displayln""))

```

Ungolfed:

```
(define(f a b)
  (define (g x y)
    (if (= 1 x y) 1
        (let* ((s (for*/sum ((i (range 1 (add1 x)))
                             (j (range 1 (add1 y)))
                             #:unless (and (= i x) (= j y)))
                    (g i j)))
               (a (/ s (* x y)))
               (b (/ (add1 s) (* x y)))
               (c (/ 1 (+ x y))))
          (if (< (abs(- a c))
                 (abs(- b c)))
              0 1))))
  (for ((i (range 1 (add1 a))))
    (for ((j (range 1 (add1 b))))
      (print (g i j)))
    (displayln ""))
  )

```

Testing:

```
(f 8 8)

```

Output:

```
10000000
00000100
00100000
00000000
00001000
01000000
00000000
00000000

```

# Answer
> 0 votes
# Perl, 151 + 1 = 152 bytes

Run with the `-n` flag. The code will only work correctly every *other* iteration within the same instance of the program. To get it to work correctly every time, add 5 bytes by prepending `my%m;` to the code.

```
for$b(1..$_){for$c(1..$_){$f=0;for$d(1..$b){$f+=$m{"$d,$_"}/($b*$c)for 1..$c}$g=1/($b+$c);print($m{"$b,$c"}=abs$f-$g>=abs$f+1/($b*$c)-$g?1:_).$"}say""}''

```

Readable:

```
for$b(1..$_){
    for$c(1..$_){
        $f=0;
        for$d(1..$b){
            $f+=$m{"$d,$_"}/($b*$c)for 1..$c
        }
        $g=1/($b+$c);
        print($m{"$b,$c"}=abs$f-$g>=abs$f+1/($b*$c)-$g?1:_).$"
    }
    say""
}

```

Output for input of 100:

```
[encoded data, 10000 characters]

```

# Answer
> 0 votes
# Wolfram Language (Mathematica), 180 bytes

```
(a=SparseArray[{1,1}->1,{#,#},-1];({x,y}={##};If[(t=a[[##]])<0,s=0;Do[If[{i,j}!={##},s+=#0[i,j]],{i,#1},{j,#2}];l=s(q=1/x/y)-1/(x+y);r=l+q;a[[##]]=If[Abs@r>Abs@l,0,1],t])&[#,#];a)&

```

Try it online!

Recursive approach: start from array filled with undefined `-1` items and `1` for first item.
For `n` 20-30 as faster, as Python.
Full version self-explained:

```
Clear[m];
n = 15;
arr = SparseArray[{1, 1} -> 1, {n, n}, -1];
m[x_, y_] :=
  If[(current = arr[[x, y]]) < 0,

   total = 0; Do[total += m[i, j], {i, x}, {j, If[i == x, y - 1, y]}];
   tmp1 = total/x/y - 1/(x + y); tmp2 = tmp1 + 1/x/y;
   arr[[x, y]] = If[Abs@tmp2 > Abs@tmp1, 0, 1]

   , current
   ];
m[n, n];
StringJoin[Append[#, "\n"] & /@ (Normal@arr /. {1 -> "*", 0 -> " "})]

```

---
Tags: code-golf, matrix
---


title: Join my exclusive friendly club!

text:
# Question
Title: Join my exclusive friendly club!
Two or more positive integers are said to be "friendly" if they have the same "abundancy". The abundancy of an positive integer \\$n\\$ is defined as $$\frac {\sigma(n)} n,$$ where \\$\sigma(n)\\$ is the sum of \\$n\\$'s divsors. For example, the abundancy of \\$30\\$ is \\$\frac {12} 5\\$ as

$$\frac {\sigma(30)} {30} = \frac {1 + 2 + 3 + 5 + 6 + 10 + 15 + 30} {30} = \frac {72} {30} = \frac {12} 5$$

Because \\$140\\$ has the same abundancy (\\$\frac {12} 5\\$), we know that \\$30\\$ and \\$140\\$ are "friendly". If a number does not have the same abundancy of any other numbers, it is termed a "solitary" number. For example, \\$3\\$'s abundancy is \\$\frac 4 3\\$ and it can be shown that no other number has an abundancy of \\$\frac 4 3\\$, so \\$3\\$ is solitary.

We can partition the positive integers into "clubs" of friendly numbers. For example, the perfect numbers form a club, as they all have abundancy \\$2\\$, and solitary numbers each form a club by themselves. It is currently unknown whether or not infinitely large clubs exist, or if every club is finite.

---

You are to take two positive integers \\$n\\$ and \\$k\\$, and output \\$k\\$ numbers in \\$n\\$'s club. You may assume that \\$k\\$ will never exceed the size of the club (so \\$k\\$ will always be \\$1\\$ for solitary numbers etc.). You may output any \\$k\\$ numbers, so long as they all belong to \\$n\\$'s club (note that this means you do not always have to output \\$n\\$). You may input and output in any reasonable format and manner \- keep your golfing in your code, not your I/O.

**A few remarks**

* You may assume that \\$n\\$ is known to be either friendly or solitary - you will never get e.g. \\$n = 10\\$.
* It has been shown that if \\$\sigma(n)\\$ and \\$n\\$ are co-prime, \\$n\\$ is solitary, and so, in this case, \\$k = 1\\$.
* Your answers may fail if values would exceed the limit of integers in your language, but only if that is the *only* reason for failing (i.e. if your language's integers were unbounded, your algorithm would never fail).
* I am willing to offer a bounty for answers that also include a program that aims to be quick, as well as correct. A good benchmark to test against is \\$n = 24, k = 2\\$ as the smallest friendly number to \\$24\\$ is \\$91963648\\$

This is a challenge, so the shortest code in each language wins.

---

## Test cases

Note that the outputs provided are, in some cases, sample outputs, and do not have to match your outputs

```
n, k -> output
3, 1 -> 3
6, 4 -> 6, 28, 496, 8128
8, 1 -> 8
24, 2 -> 24, 91963648
84, 5 -> 84, 270, 1488, 1638, 24384
140, 2 -> 30, 140
17360, 3 -> 210, 17360, 43400

```

# Answer
> 12 votes
# Jelly, ~~11~~ 10 bytes

*-1 thanks to @Jonathan Allan.*

```
1,Æs×ṭʋE¥#

```

Try it online!

### Explanation

Jelly's `#` parsing is *really* confusing. `#` doesn't consume the first link `1`, since it's a nilad. (This, as it turns out, works really weirdly if you use chain separators; the equivalent code would be `ø1ð,,Æs$ÆḊ¬ð#`.)

The code is essentially parsed from postfix notation to the following, where `[]` represent chains:

```
[1 #(filter=¥[ʋ[, Æs × ṭ] E])]

```

This chain is then applied to the arguments `(n, k)`. The value is first initialized to `n`.

The `#` operation is then used as a dyad, as if it's the `+` in `1+`. It receives `(1, n)` as arguments and starts passing those to its `filter` chain, incrementing the `1` until `k` matches are found. (Since `#` only consumed one link, the last command-line argument is used as the count.)

The filter chain then does this, where `x` is the candidate number:

* `,`: make pair `[x, n]`.
* `Æs`: compute `[sigma(x), sigma(n)]`.
* : make pair `[n, x]`.
* `×`: elementwise multiply, i.e. `[sigma(x)*n, sigma(n)*x]`.
* `E`: see if the values equal. This is pretty clearly true iff `x/sigma(x)=n/sigma(n)`.

# Answer
> 5 votes
# Husk, ~~11~~ 10 bytes

```
↑f¤=oṁ\Ḋ⁰N

```

Try it online!

```
↑f¤=S/oΣḊ⁰N
 f        N  # filter the natural numbers by
  ¤          # combin: '¤fgxy' means 'f(g x)(g y)', where
   =         #  f is '=' equals
    oṁ\Ḋ     #  g is 'oṁ\Ḋ', which parses as:
    o        #   compose
     ṁ       #    map this & sum the results:
      \      #     reciprocal
       Ḋ     #    over each divisor of argument
        ⁰    #  x is the last input argument
             #  y is the number being filtered (so, each of the natural numbers)
↑            # finally, from the filtered numbers, take
             # the first n equal to the other input argument.

```

# Answer
> 4 votes
# Ruby, ~~90~~ 79 bytes

```
->n,k{w=0;g=->w{(1..w).sum{|x|w%x<1?x:0}};k.times{g[w+=1]*n==g[n]*w||redo;p w}}

```

Try it online!

# Answer
> 3 votes
# PARI/GP, 55 bytes

```
f(n,k,i)=while(k,sigma(n)/n-sigma(i++)/i||k-=!print(i))

```

Attempt This Online!

This is slow. It tries every positive integer one by one until it finds `k` answers. It takes 3 minutes to calculate `f(24, 2)` on my computer.

# Answer
> 3 votes
# JavaScript (V8),  ~~91 89 88~~  85 bytes

*Saved 3 bytes thanks to @tsh*

Expects `(n)(k)`. Prints the numbers.

```
n=>k=>{for(g=x=>{for(q=d=x;--d;)x%d?0:q+=d},i=0;k;q*++i+~g(i)*q*n||print(i)|k--)g(n)}

```

Try it online!

### Commented

```
n =>                   // n = positive integer
k => {                 // k = required number of solutions
  for(                 // main loop:
    g = x => {         //   g is a helper function loading sigma(x) in q
      for(             //   loop:
        q = d = x;     //     start with q = d = x
        --d;           //     decrement d and stop when d = 0
      ) x % d ? 0      //     add d to q if d is a divisor of x
              : q += d //
    },                 //   end
    i = 0;             //   start with i = 0
    k;                 //   stop when k = 0
    q * ++i +          //   increment i and test whether:
    ~g(i) * q * n ||   //     sigma(n) * i = sigma(i) * n
    print(i) | k--     //   if so, print i and decrement k
  ) g(n)               //   load sigma(n) in q
}                      // end

```

# Answer
> 3 votes
# 05AB1E, 10 bytes

```
µN‚ÂÑO*ËD–

```

Inputs in the order \\$k,n\\$, outputs the results on separated newlines to STDOUT.

Port of *@PurkkaKoodari*'s Jelly answer.

Try it online or verify almost all test cases (times out for `2,24`).

**Explanation:**

```
µ           # Loop while `¾` is not equal to the first (implicit) input-integer:
            # (`¾` is 0 by default)
 N‚         #  Pair the loop-index with the second (implicit) input-integer
   Â        #  Bifurcate it; short for Duplicate & Reverse copy
    Ñ       #  Map both values in the reversed copy to a list of its divisors
     O      #  Sum those inner lists of divisors
      *     #  Multiply it to the pair
       Ë    #  Check if both values in the pair are the same
        D   #  Duplicate this check
         –  #  Pop, and if this is truthy: print `N` with trailing newline
            #  (implicit - Pop, and if this is truthy: increase `¾` by 1)

```

# Answer
> 3 votes
# , ~~74~~ 72 bytes

```
\(n,k,s=\(m,l=1:m)mean(l*!m%%l))while(k)s(F<-F+1)==s(n)&&{show(F);k=k-1}
```

Attempt This Online!

# Answer
> 2 votes
# Charcoal, 44 bytes

```
ＮθＮη≔⁰ζＷ‹ⅉη«≦⊕ζ¿⁼×ζΣΦ⊕θ∧κ¬﹪θκ×θΣΦ⊕ζ∧κ¬﹪ζκ⟦Ｉζ

```

Try it online! Link is to verbose version of code. Don't try any of the other test cases on TIO because it's too slow. Explanation:

```
ＮθＮη

```

Input `n` and `k`.

```
≔⁰ζ

```

Start enumerating the club.

```
Ｗ‹ⅉη«

```

Repeat until `k` numbers have been output.

```
≦⊕ζ

```

Increment the number to be tested.

```
¿⁼×ζΣΦ⊕θ∧κ¬﹪θκ×θΣΦ⊕ζ∧κ¬﹪ζκ

```

If it's in the club, then...

```
⟦Ｉζ

```

... output it on its own line.

Save 2 bytes by dropping support for `n=1`:

```
ＮθＮη≔¹ζＷ‹ⅉη«≦⊕ζ¿⁼×ζΣΦθ∧κ¬﹪θκ×θΣΦζ∧κ¬﹪ζκ⟦Ｉζ

```

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

# Answer
> 2 votes
# Desmos, 122 bytes

```
o->join(o,a),T->T+sign(k-o.length)
n=\ans_0
k=\ans_1
o=[]
T=0
a=\{f(T)=f(n):[T],[]\}
f(K)=\sum_{N=1}^K\{\mod(K,N)=0,0\}N/K

```

Input in the first two lines of the graph (`n` on the first line, `k` on the second)

Output is the value of `o` after the program has completely ran (which is when `T` stops incrementing)

Try It On Desmos!

Try It On Desmos! - Prettified

# Answer
> 2 votes
# 05AB1E, 9 bytes

```
µN‚ÑzOËD–

```

Try it online!

Uses that simplification that the "sum of divisors of x, divided by x" is just equal to "sum of reciprocals of divisors of x".
Apart from this, the rest of the 05AB1E nuts & bolts are shamefully stolen from Kevin Cruijssen's answer.

# Answer
> 1 votes
# Factor \+ `lists.lazy math.primes.factors math.unicode`, 78 bytes

```
[ [ dup divisors Σ swap / ] tuck call '[ @ _ = ] 1 lfrom swap lfilter ltake ]

```

Try it online!

## Explanation

Naive algorithm. Takes input as `k n` and returns a `k`-long lazy list containing numbers in the same club as `n`.

```
                           ! 4 6
[ dup divisors Σ swap / ]  ! 4 6 [ dup divisors Σ swap / ]  (push abundancy function)
tuck                       ! 4 [ dup divisors Σ swap / ] 6 [ dup divisors Σ swap / ]
call                       ! 4 [ dup divisors Σ swap / ] 2
'[ @ _ = ]                 ! 4 [ dup divisors Σ swap / 2 = ]
1 lfrom                    ! 4 [ dup divisors Σ swap / 2 = ] L{ 1 2 3 ... }
swap                       ! 4 L{ 1 2 3 ... } [ dup divisors Σ swap / 2 = ]
lfilter                    ! 4 L{ 6 28 496 8128 ... }
ltake                      ! L{ 6 28 496 8128 }

```

# Answer
> 1 votes
# Python, 116 bytes

```
def f(n,k):
 x=lambda n:sum([i for i in range(1,n+1)if n%i==0])/n;i=1
 while k:
  if x(i)==x(n):print(i);k-=1
  i+=1

```

Pretty basic but painfully slow. Calculates the abundancy of each integer from 1 to `n` using the `x` function until the chosen number of matches have been found.

# Answer
> 1 votes
# Python 3, 109 bytes

```
a=lambda n:sum(-~i*(n%-~i<1)for i in range(n))/n
def f(n,k,i=1):
 if a(n)==a(i):print(i);k-=1
 f(n,k*k/k,i+1)

```

Try it online!

A little longer one-liner,

```
def f(n,k,i=1,a=lambda n:sum(-~i*(n%-~i<1)for i in range(n))/n):print(end=(f"{[i,k:=k-1][0]}\n"if a(n)==a(i)else""));f(n,k*k/k,i+1)

```

Both functions always ends in a error(division by 0) after printing the answers.

# Answer
> 1 votes
# Haskell, 85 bytes

```
f=fromIntegral
a n=f(sum[y|y<-[1..n],n`mod`y==0])/f n
n!k=take k[x|x<-[1..],a n==a x]
```

Attempt This Online!

`!` is the infix function that implements the friendly club function.

Some testcases are commented out because this is very slow.

-3 bytes from caird.

# Answer
> 1 votes
# C (gcc), 99 bytes

```
d;c;s(n){for(d=c=n;--d;)c+=n%d?0:d;d=c;}i;f(n,k){for(i=1;k;++i)s(n)*i-n*s(i)?:printf("%d ",i,--k);}

```

Try it online!

# Answer
> 1 votes
# Wolfram Language(Mathematica), 112 bytes

Golfed version. Try it online!

```
Module[{a,b,i=1,r={}},a=DivisorSigma[1,n]/n;While[Length@r<k,b=DivisorSigma[1,i]/i;If[a==b,r~AppendTo~i];i++];r]

```

Ungolfed version. Try it online!

```
f[n_, k_] := Module[{a, b, i = 1, r = {}},
  a = DivisorSigma[1, n]/n;
  While[Length[r] < k,
   b = DivisorSigma[1, i]/i;
   If[a == b, AppendTo[r, i]];
   i++
  ];
  r
]

f[3, 1]//Print
f[6, 4]//Print
f[8, 1]//Print
(*f[24, 2]//Print*)
f[84, 5]//Print
f[140, 2]//Print
f[17360, 3]//Print

```

# Answer
> 0 votes
# Japt v2.0a0, 17 bytes

```
@â x÷U ¶Xâ x÷X}jV

```

Try it

---
Tags: code-golf, sequence, number-theory
---


title: Create an ASCII line, given a length

text:
# Question
Title: Create an ASCII line, given a length
## Information

Create a diagonal line given its length (let’s call the variable, say, \\$n\\$ where \\$n \> 0\\$)

* The diagonal line starts from the top left and goes to the bottom right.
* You **must** use the ASCII character `\` for the line.
* The input number can be given from STDIN or if your program doesn’t support that, use a hardcoded value in your code or pass it as an argument while running the program.
* For padding, **only use** the **space character** `0x20`
* *Trailing spaces* and/or *newlines* are **allowed**.
* The **length** of the line is the **non whitespace** characters

Here is an example program (59 bytes):

```
n = int(input())
for i in range(n):
  print(' ' * i + '\\')

```

Try it online!

Example:

```
Input: 4
Output
\
 \
  \
   \

```

### Rules

* Use *standard* I/O when possible.
* Standard *loopholes* are forbidden.
* This is code golf, so the shortest answer in bytes wins.
* Please explain the code that you wrote.

# Answer
# Canvas, 1 byte

Better tool for the job ;)

Try it here!

Given an integer, this draws a diagonal of that string. If you pass a string instead, this prints the string along the diagonal. There is matching anti-diagonal builtin  as well.
> 26 votes

# Answer
# Charcoal, 2 bytes

```
↖Ｎ

```

Try it online!

right tool for the job
> 10 votes

# Answer
# APL (Dyalog Unicode), 9 bytes (SBCS)

Anonymous tacit prefix function. Returns a list of string, as per meta consensus.

```
'\'↑⍨¨-∘⍳

```

Try it online!

`∘⍳` indices one through \\$n\\$, then:

`-` negate those

`¨` for each:

`↑⍨` take (when negative: from the rear) that many characters (padding with spaces) from:

`'\'` the backslash character
> 7 votes

# Answer
# Jelly, 7 bytes

```
=þị⁾\ Y

```

Try it online!

```
Ḷ⁶ẋp”\Y

```

Try it online!

## How they work

```
=þị⁾\ Y - Main link. Takes N on the left
=þ      - Yield the identity matrix of size N
  ị⁾\   - Index into "\ ", replacing 1 with "\" and 0 with " "
      Y - Join by newlines

```

```
Ḷ⁶ẋp”\Y - Main link. Takes N on the left
Ḷ       - Range [0, ..., N-1]
 ⁶ẋ     - Repeat that many spaces for each
   p”\  - Append "\" to each
      Y - Join by newlines

```
> 6 votes

# Answer
# Japt `-R`, 5 bytes

```
õ!ù'\

```

Try it

```
õ!ù'\     :Implicit input of integer
õ         :Range [1,input]
 !ù'\     :For each, left pad "\" to that length with spaces
          :Implicit output joined with newlines

```

# Japt `-mR`, 5 bytes

```
'\iUç

```

Try it

```
'\iUç     :Implicit map of each U in the range [0,input)
'\i       :Prepend to "\"
   Uç     :  Space repeated U times
          :Implicit output joined with newlines

```
> 6 votes

# Answer
# 51AC8, 10 bytes

```
R[\ ×\\+t]

```

Try it Online!

*-2 bytes* due to an update.

*-7 bytes* due to an update introducing for\_each loops and range.

*-1 byte* online interpreter and implicit input.

## Explanation

```
       # Implicit Input (STDIN) and push to stack
R      # Range from 0 to input (exclusive)
[      # Start for each
  \    # Push ' ' to the stack
  ×    # Multiply the top 2 elements on the stack
  \\   # Push '\'
  +    # Add top 2 elements
  t    # Pop and print top of stack
]      # End of while loop

```
> 6 votes

# Answer
# Python 2, 37 bytes

```
x='\\'
exec'print x;x=" "+x;'*input()

```

Try it online!
> 5 votes

# Answer
# C (clang), 37 bytes

```
f(n){printf("%*c\n",n--,92,n&&f(n));}

```

Try it online!

---

# C (gcc), 39 bytes

A recursive version suggested by @att.

```
f(n){--n&&f(n);printf("%*c\n",n+1,92);}

```

Try it online!

---

# C (gcc), 44 bytes

```
i;f(n){for(i=0;i++<n;)printf("%*c\n",i,92);}

```

Try it online!
> 5 votes

# Answer
# Dyalog APL, ~~16~~ 14 bytes

Solution - Takes in number of lines as input from user, and returns a string of diagonal line.

`' \'[1+∘.=⍨⍳⎕]`

### Explanation

```
⎕            ⍝ ⎕ takes input from the user (number of lines)
             ⍝ In the below explanation, I have assumed ⎕ = 9 as input
⍳⎕            ⍝ 1 to 9 : [1,2,3,4,5,6,7,8,9]
∘.=          ⍝ Outer Product with Equality
⍨            ⍝ Apply a function with same argument on both sides
∘.=⍨⍳⎕       ⍝ ∘.=⍨ function applied to array ⍳⎕ = [1,2..9]
             ⍝ This is same as (⍳9) ∘.= (⍳9), which produces Identity Matrix of size 9
1+∘.=⍨⍳⎕     ⍝ Add 1 to each element of previous matrix (since APL uses 1-based index)
' \'[1+∘.=⍨⍳⎕] ⍝ From the string ' \', select characters specified by indices in 1+∘.=⍨⍳⎕

```
> 5 votes

# Answer
# brainfuck, 113 bytes

```
,>>+++++++[<+++++++++++++>-]<+>++++++++++>>++++[<++++++++>-]<<<<[>>>>[->+>+<<]>[-<+>]>[<<<.>>>-]<<<<<.>.>>+<<<<-]

```

Try it online.

First time poster. This was a fun exercise! Please provide criticism, I pretty much went in cold when writing this.

```
, how long the line should be via char code
>

initialize cell 1 with "\"
>+++++++[<+++++++++++++>-]<+
>

initialize cell 2 with "\n"
++++++++++
>

initialize cell 3 with " "; go back to beginning
>++++[<+++++>-]<
<<<

start loop at cell 0
[
    >>>> go to cell 4
    [
        ->+>+<< copy the pad value to cells 5 and 6
    ]

    > now we move cell 5 to cell 4
    [
        -<+> cell 4 keeps track how much padding we'll need for our next iteration
    ]
    >

    cell 6 keeps track of how many spaces we need to print currently
    [
        <<<  go to space char
        .    print it
        >>>- decrease counter
    ]

    <<<<< move to line char
    .>.   print line and newline
    >>+   move to cell 4 and increase our padding by 1
    <<<<- back to cell 0; subtract line counter
]

```
> 5 votes

# Answer
# Jelly, 7 bytes

```
Ṭ€ị⁾\ Y

```

Try it online!

~~Working on golfing. This is longer than I remember it being possible.~~ The JHT exercise allows other characters so I can't get this to 5 bytes because of that :/

```
Ṭ€ị⁾\ Y    Main Link
 €         For each (implicit range)
Ṭ          Generate a boolean list with 1s at the indices
  ị        Index that into
   ⁾\      "\ "
      Y    and join on newlines

```
> 4 votes

# Answer
# , 10 bytes

```
' \'{~=@i.

```

Try it online!
> 4 votes

# Answer
# C (clang), ~~90~~ ~~77~~ 60 bytes

```
i;main(n){for(scanf("%i",&n);i<n;printf("%*s\\\n",i++,""));}

```

Try it online!

My first work without `int` in it while still using it. I'm doing better now, aren't I?

Thanks to att for golfing 13 bytes. Thanks to ceilingcat for golfing 17 bytes.
> 4 votes

# Answer
# convey, 46 bytes

```
[0>>,+1
   v"^
{,"=@#]}
 >^}"~v#'\\'
' '!""~/}

```

Try it online!

Visualization (i use '\_' instead of space because the gif doesnt show the space char if i use it, but in the official page the output works whit spaces):
> 4 votes

# Answer
# Vyxal `M`, 7 bytes

```
(nI\\+,

```

Try it Online!

Explanation:

```
(  # range from 0 to implict input
  n  # loop variable
   I  # push that many spaces
    \\  # backslash literal
      +  # concatenate the spaces with the backslash
       ,  # print

```
> 4 votes

# Answer
# 05AB1E, 4 bytes

```
'\3Λ

```

Try it online!

Using the input as length, draw `\` in direction `3` (down-right) with the canvas builtin `Λ`. See Kevin's tip for details on how the canvas works

---

6 bytes without the canvas builtin:

```
'\ILj»

```

Try it online!

For each number in the range `IL == [1..input]`, pad the string `"\"` with leading spaces to this length (`j`). `»` joins the results by newlines.

Another 6 bytes solution suggested by Kevin Cruijssen:

```
L<'\ú»

```

Try it online!

For each number in the range `L< == [0..input-1]`, pad the string `"\"` with that many leading spaces.
> 3 votes

# Answer
# JavaScript (ES6), 33 bytes

```
f=(n,s=`\\
`)=>--n?s+f(n,' '+s):s

```

Try it online!
> 3 votes

# Answer
# MATLAB/Octave, ~~32~~ 31 bytes

*-1 byte thanks to Luis Mendo*

```
disp([60*eye(input(''))+32,''])

```

Try it online!
Reads the length from standard input, writes to standard output.
Makes use of identity matrix `eye(x)`.

---

Alternatively, using function input/output, **~~22~~ 21 bytes**:

```
@(x)[60*eye(x)+32,'']

```

Try it online!
Anonymous function, outputs character array.
> 3 votes

# Answer
# Stax, 3 bytes

```
■♦9

```

Run and debug it

## Explanation

```
m'\)
m    map 1..n and print with newlines
 '\) pad \ on the left with spaces to given length

```
> 3 votes

# Answer
# Python 3.8 (pre-release), 46 bytes

```
for i in range(int(input())):print(' '*i+'\\')

```

Try it online!
> 2 votes

# Answer
# , ~~42~~, 39 bytes

* -3 bytes thanks to @Dominic van Essen

```
write(strrep("\\",diag(x<-scan())),1,x)

```

Try it online!

**Explanation:**

* take x from standard input,
* create a diagonal matrix of size x
* repeat the character `'\'` one time for each 1 of the matrix and 0-times for each 0 (= empty string)
* print the matrix separating each character with a space
> 2 votes

# Answer
# Vyxal `jṀ`, 4 bytes

```
ƛ\\꘍

```

Try it Online!

Flags go brrr

```
ƛ\\꘍   Full Program
ƛ      For each (implicity loops from 0 to n - 1)
 \\    push '\'
   ꘍   prepend x spaces to '\'

```

is equivalent to `mM`, which makes implicit range start at `0` instead of `1` and end at `n - 1` instead of `n`.

`j` joins the top of the stack on newlines at the end.
> 2 votes

# Answer
# Red, 30 bytes

```
repeat i n[print pad/left"\"i]

```

Try it online!
> 2 votes

# Answer
# Java, 56 bytes

```
n->{for(var s="\\";n-->0;s=" "+s)System.out.println(s);}

```

Try it online!
> 2 votes

# Answer
# CJam, 10 bytes

```
ri{S*'\N}%

```

Try it online!

### Explanation

```
r             e# Read input
 i            e# Evaluate as an integer, n
  {     }%    e# Do the following for each k in [0 1 ... n-1]
              e# Push k (implicit)
   S          e# Push space
    *         e# Repeat. Gives a string with k spaces
     '\       e# Push character "\"
       N      e# Push newline
              e# Output the stack (implicit)

```
> 2 votes

# Answer
# , 35 bytes

```
cat(sep="\\
",strrep(" ",0:scan()))

```

Try it online!
> 2 votes

# Answer
# PHP, 58 57 bytes

```
for($i=0;$i<$argv[1];$i++)echo str_repeat(' ',$i)."\\\n";

```

Try it here!

This is my first golf, so feel free to mention anything I can do to improve this!
> 2 votes

# Answer
# Factor, 40 bytes

```
[ iota [ [ bl ] times "\\"print ] each ]

```

Try it online!
> 2 votes

# Answer
# Perl 5, 34 bytes

```
s//\\/;$==<>;s// / while(say,$=--)

```

Try it online!

This should be run from the command line like `perl -E 's//\\/;$==<>;s// / while(say,$=--)'` to activate the `say` feature without adding any bytes.

Ungolfed:

```
$_='\\'; #Set the default variable $_ to a single backslash
$==<>; #Take input into $=. This variable converts the input to an integer
while($=--){ #Decrement $= and loop
    say; #Prints $_ and a newline
    $_=" $_"; #Adds a space to the start of $_
}

```

Uses `s// /` as shorthand for `$_=" $_"` (i.e. to prepend a space to `$_`). Putting `say` into the while loop lets us drop the brackets from the loop body.
> 2 votes

# Answer
# Ruby, 41 bytes

```
puts Array.new(gets.to_i){|i|(' '*i+'\\')}

```

Try it online!
> 2 votes

# Answer
# AWK, 34 bytes

```
{for(;$1--;x=x" ")y=y x"\\\n"}$0=y

```

Try it online!

This is pretty straightforward I suppose... Each time through the loop creates a string corresponding to one line of output. The control just counts decrements the first commandline argument until it's 0.

```
 for(;$1--;      )

```

The body of the loop appends the current output line to an accumulator variables, taking the current "padding" of blanks and appending `\` and '\n\` to it.

```
                  y=y x"\\\n"

```

The "end of loop" expression builds up the padding variable.

```
           x=x" "

```

Then once all the lines have been generated, assigning that output string to `$0` as a truthy test, without an action, causes the output to be printed.

```
                               $0=y

```

# Ly, 24 bytes

```
0(10)'\<n[>&:[o]p' <1-]<

```

Try it online!

This is really a translation of the approach, just in Ly. So I'm not adding a separate entry for it.

The first task is to push a null terminated string `\\n` onto the stack.

```
0(10)'\

```

Then shift to a new stack and read in the number of lines.

```
       <n

```

The construct to loop that many times shifts between stacks a decrements the top of the stack with the loop counter until it hits 0.

```
         [>        <1-]

```

The body of the loop, duplicates the stack with the output string on top of itself `&:` then prints up to the first `\0`, deletes that null and adds a space. So each iteration prints the current line and appends a space to the front in anticipation of the next iteration.

```
           &:[o]p'

```

When the loop ends and all the lines have been printed, we just need to switch stacks to avoid printing what's left.

```
                       <

```
> 2 votes

# Answer
# **BQN**, 12 bytesSBCS

```
↕⌽⁼⎉0‿1↑⟜"\"

```

Try it here.

```
↕⌽⁼⎉0‿1↑⟜"\" # tacit function which takes an int and returns a character array
       ↑⟜"\" # take input number of characters from the string "\", padding with spaces
 ⌽⁼          # rotate-inverse (right instead of left),
   ⎉0‿1      #   rank 0‿1 (each scalar on the left pairs with a vector on the right)
↕            # by the indices 0 ... input

```
> 2 votes

# Answer
# Lolwho.Cares, 183 bytes

```
* >2,*1210+10 0*+ 0>,02001*101v
                   ^ 010121   <
  ^           121021<
    >*+102021**+vv             <
v 120210021`1012<   +**120021 <
>*101*10102 2012 >*1012+201020`^

```

Given a decimal number N, will output a line of length N.

Explanation:

```
* >2,*1210+10 0*+ 0>,02001*101v
                   ^ 010121   <
  ^           121021<

```

This code reads from the input, and converts ascii decimal to a number. Side effect of it's working means it pushes N, followed by 0.

It does so by first reading a character, finishing when it read 0 (EOF). It then multiplies the current number by 10, and finally it subtracts 48 from the ASCII value and adds.

```
    >*+102021**+vv             <
v 120210021`1012<   +**120021 <
>*101*10102 2012 >*1012+201020`^

```

This code takes \[N, 0\] pushed by the other function and draws a line accordingly. This makes use of the fact that the stack is "initialised" with an infinite amount of 0s at the bottom.

This is basically an implementation of nested for loops; It checks whether enough lines have been printed, then prints X spaces, followed by \ and newline.

The language is a custom esoteric programming language, similar to BEFUNGE (as user pointed out here).

Note: Due to the implementation of number reading, care must be taken to omit any non-decimal characters, including leading/trailing spacing/newlines.

Online interpreter
> 2 votes

# Answer
# Raku, 22 bytes

```
{[~] (' 'Xx^$_)X~'\
'}

```

Try it online!

`' ' Xx ^$_` generates a list of the spaces starting each line. `X~ '\␤'` appends a backslash and newline to each of those strings, then `[~]` concatenates them.
> 2 votes

# Answer
# Regenerate `-l`, 4 bytes

```
 *\\

```

Takes input as the argument to the `-l` flag; for example,

```
python3 regenerate.py -r ' *\\' -l 4
\
 \
  \
   \

```

Try it here!

### Explanation

The regex  `*\\` matches 0 or more spaces, followed by a backslash. Regenerate finds all strings that match that regex, starting from the shortest: `\`,  `\`,  `\`, and so forth. By default, each match is printed on its own line, and the `-l N` option limits the output to the first N matches.
> 2 votes

# Answer
# Mathematica, 39 bytes

We save some bytes by using an infix `Array` over `Range`, `Table` over `StringRepeat`, and `Echo` over `Print`.

We also cut it down to 33 bytes in TIO, because user input for Mathematica wasn't working :)

```
Echo[Table[" ",#]<>"\\"]&~Array~Input[]

```

Try it online!
> 2 votes

# Answer
# BQN, ~~14~~ 11 bytesSBCS

```
" \\"⊏˜↕=⌜↕

```

Run online!

*¯3 thanks to @ovs*
> 2 votes

# Answer
# Lua, 42 bytes

```
for i=1,...do print((" "):rep(i).."\\")end

```

Try it online!
> 2 votes

# Answer
# Kotlin, 56 Bytes

Try it online!

```
fun d(a:Int){var t="";repeat(a){println(t+'\\');t+=" "}}

```

ungolfed version
I think this code is obvious enough

```
fun d(a:Int)
{
    var t = ""
    repeat(a)
    {
        println(t + '\\')
        t += " "
    }
}

```
> 2 votes

# Answer
# Perl 5 \+ `-n -M5.10.0`, 24 bytes

```
say$"x$_,v92 for 0..--$_

```

Try it online!
> 2 votes

# Answer
# K (ngn/k), 8 bytes

```
" \\"@=:

```

Try it online!

* `=:` generate an `n` by `n` identity matrix
* `" \\"@` index into a string containing two characters - a space, and a backslash
> 2 votes

# Answer
# Nibbles, ~~5~~ 4 bytes (8 nibbles)

*-2 nibbles thanks to a hint from Darren Smith*

```
$&" "$"\\"

```

Attempt This Online!

### Explanation

```
$&" "$"\\"
$           Input number
            (Implicit) Map over range from 1 to that number:
 &            Left-justify
      "\\"    string containing a backslash
     $        to a width given by the function argument
  " "         by padding with spaces
            Output each element of that list on a separate line (implicit)

```
> 2 votes

# Answer
# Vyxal `j`, 6 bytes

```
ʁð*\\+

```

Try it Online!

```
ʁð*\\+
ʁ         Push range(input)
  *       Repeat...
 ð        the string ' ' that many times for each
   \\+    Append a backslash to each

j flag: join on newlines

```
> 1 votes

# Answer
# Python 3, 42 bytes

```
f=lambda n,s="\\\n":n*s and s+f(n-1,' '+s)

```

Try it online!

-2 bytes thanks to @ovs
> 1 votes

# Answer
# Retina 0.8.2, 13 bytes

```
.+
$*

$`\¶

```

Try it online! Note: Trailing spaces on lines 2 and 3. Explanation:

```
.+
$*

```

Convert the input to a string of spaces.

```

$`\¶

```

Output each prefix of the string followed by a `\`, on its own line.

This program outputs two trailing newlines, one from the code, one from Retina 0.8.2's default output. The latter can be suppressed at a cost of 2 bytes by changing the third line to `\`` . Alternatively the following 14-byte Retina 1 program outputs no trailing newlines:

```
.+
*
L$`
$`\

```

Try it online! Note: Trailing spaces on lines 2 and 3. Explanation: Much like the Retina 0.8.2 program, except the repetition operator is simply `*` and the list matches command only inserts newlines between the substitutions.
> 1 votes

# Answer
# Julia 1.0, ~~26~~ 21 bytes

thanks dingledooper for challenging my answer

```
!n=" ".^(0:~-n).*"\\"

```

Try it online!
> 1 votes

# Answer
# PowerShell, 25 bytes

```
1..$args[0]|%{' '*$_+'\'}

```

Try it online!

thats why i love powershell
> 1 votes

# Answer
# Bash, 39

```
printf %*s\\n $(eval echo {1..$1}\\ \\)

```

Try it online!
> 1 votes

# Answer
# Zephyr, 80 bytes

```
set s to" "
input n as Integer
for i from 1 to n
print s+"\"
set s to s+" "
next

```

Try it online!
> 1 votes

# Answer
# Ruby, 31 Bytes

```
gets.to_i.times{|i|p' '*i+'\\'}

```

Works in much the same way as the example code but more rubified
> 1 votes

# Answer
# Risky, 20 bytes

```
0?+0+_0+0_?+*{*_?+0__?+0+_0+0+_:-+!_/+/

```

Try it online!

I'm not happy with the byte count.
> 1 votes

# Answer
# JavaScript (Node.js), 57 bytes

```
f=n=>{for(i=0;++i<n+1;){console.log(" ".repeat(i)+"\\")}}

```

Try it online!
> 1 votes

# Answer
# Batch, 88 bytes

```
@setlocal enabledelayedexpansion&set s=\&for /l %%i in (1,1,%1)do @(echo !s!
set s= !s!)

```

Takes input from the command line.
> 1 votes

---
Tags: code-golf, ascii-art
---