text:
Sum a Cubically cube's faces
Manually summing a Cubically cube's faces is tedious and time-consuming, sorta like writing code in Cubically itself.
In Most efficient cubifier, I asked you to translate ASCII to Cubically source. One of the answers there uses a cube initialization sequence and then modifies the resulting cube based on the sums of the pre-initialized cube. This method has been used in many Cubically-related programs since. When testing a new initialization sequence, one has to add up all the values on all the faces, which usually takes two or three minutes.
Your task is to automate this process for us!
You will take two inputs, an integer n and a string c. These may be read from command line arguments, function arguments, standard input, a file, or any combination of those. c will be a Cubically memory cube of size n as pretty-printed by the interpreter.
The Cubically interpreter dumps its cube to STDERR upon program termination, formatted nicely for simple viewing. Run an empty program in the Cubically interpreter and open the debug section to see the cube dump of an initialized cube. Add an argument 4 to see a 4x4x4, or 5 to see a 5x5x5, etc.
If n is 3, c will follow this format (the integers will be variable):
   000
   000
   000
111222333444
111222333444
111222333444
   555
   555
   555

Spaces, newlines, and all. If n is 4, c will look like this (also with variable integers):
    0000
    0000
    0000
    0000
1111222233334444
1111222233334444
1111222233334444
1111222233334444
    5555
    5555
    5555
    5555

Et cetera.
Your program will output six integers. The first integer will be the sum of all the numbers on the top face.
   000
   000          top face
   000
111222333444    left, front, right, and back faces, respectively
111222333444
111222333444
   555
   555          bottom face
   555

The second integer will be the sum of the left face, the third the front, the fourth the right, the fifth the back and the sixth the bottom.
So if n was 3 and c was this:
   242
   202
   242
000131555313
010121535343
000131555313
   424
   454
   424

Your program would output 20 1 14 43 24 33.
Additional rules:

The output integers must be delimited by non-integer characters. You may also choose to return an array.
You may assume that the input is correct - n is an integer and c is a cube from Cubically's debugging output. So if n was 3.0 and c was foo bar, your program could break and still be valid.
Your program only needs to work for n > 1 and n < 1260. It may (attempt to) handle larger or smaller cube sizes, but it is not necessary.

This is code-golf, so the shortest code wins! If you need help, feel free to ask in the Cubically chatroom.

May we assume the input to include all trailing spaces so as to be a rectangle?

@fireflame241 if you mean n spaces after every line, no. They are not included in the dump.

We really need a "cubically" tag.

@Mr.Xcoder status completed :) I'd been thinking that too, and I'm working on four more Cubically challenges ATM.

Jelly, 16 14 13 bytes
3 bytes thanks to Erik the Outgolfer.
ḟ⁶ỴV€€sS€ẎsS€

Try it online!

Save another one by getting rid of Z: ḟ⁶ỴV€€sS€ẎsS€ (or ḟ⁶ỴV€€sS€FsS€)

Python 2, 155 150 147 123 121 120 bytes
Could probably be golfed quite a bit
Edit: -5 bytes by using a better method for removing the whitespaces
Edit: -3 bytes thanks to @Leaky Nun
Edit: -24 bytes by not removing whitespaces
Edit: -2 bytes by exploiting precedence
lambda n,a:[sum(sum(map(int,b[j*n:][:n]))for b in a.split("\n")[i*n:][:n])for i in range(3)for j in range(~i%2,i%2*2+2)]

Try it online!

05AB1E, 16 bytes
¹|ðм€Sôεø¹ô€OO}˜

Try it online!

Octave, 64 59 54 bytes
@(c,n)sum(im2col(c'-48,[n n],'distinct'))([2 5:8 10])

Try it online!
Previous answer:
@(c,n)sparse(kron((1:4)+[0;4;8],!!e(n)),1,c-48)([2 5:8 10])

Try it online!
Returns an array as output.

Not what I expected, but perfectly valid, and to be honest I didn't expect any answers at all. +1

@MDXF What did you expect?

I didn't expect this short of an answer, nor this form of accepting strings. But it's just how Octave does it; I've never used Octave.

Husk, 15 bytes
3 ṁs and 2 ms
mṁṁiṁoC⁰TC⁰mf±¶

Try it online!
Explanation
                  Takes input as two arguments, the first being n, the second, the cube
              ¶   Split second argument into a list of lines
           m      For each line
            f±    keep only the digits (remove spaces)
         C⁰       Cut into lists of length n
    ṁ             Map then concatenate
        T           transpose
     oC⁰            then cut into lists of length n
mṁṁi              Takes list of lists of strings (or, in Husk, a list of lists of lists of chars) and returns the sum of the digits in each list
m                 Map function over list of lists
 ṁ                  map then sum
  ṁ                   map then sum
   i                  convert character to integer

mṁṁi is really nice!

Perl 5, 66 + 1 (-n) = 67 bytes
$j=$k<6?$k++/3:5;s/\d{3}/';$r[$j++]+='.$&=~s|.|+$&|gr/gee}{say"@r"

Try it online!

Python 2, 137 127 bytes
-10 bytes thanks to @Halvard Hummel
lambda x,n:[sum(sum(map(int,x.split('\n')[b+j][a:a+n]))for j in range(n))for a,b in[[n,0],[0,n],[n,n],[2*n,n],[3*n,n],[n,2*n]]]

Try it online!

127

PowerShell, 236 bytes
param($n,$z)
function f($y){$y-replace' '-split'(.)'-ne''-join'+'|iex}
$a=$z-split"`n"
f $a[0..($n-1)]
$a[$n..(2*$n-1)]|%{$x="($('.'*$n))";$1,$2,$3,$4=$_-split$x-ne'';$h+=$1;$i+=$2;$j+=$3;$k+=$4}
$h,$i,$j,$k|%{f $_}
f $a[(2*$n)..(3*$n)]

Try it online!
Ooof, this is long. But, splitting and slicing of strings isn't one of PowerShell's strong suits, so I guess it's somewhat expected. Also -- So. Many. Dollars.
Takes in parameters $n and $z as the size and cube net, respectively. Then constructs a function that is used throughout. Here, we're removing spaces, splitting on each individual digit, removing the empty characters in between, joining all the characters together with a +, and then executing the resulting statement to get a number. For example, this turns "123" into 1+2+3 which when executed is 6.
The next line splits the input cube net on newlines, storing the result into array $a. We then perform the function on the first $n lines and output the top face of the cube.
For the next set, we need to splice the strings based on the cube size. So, we loop through each line, constructing $x as the appropriate regex pattern (e.g., for size $n=3 this will be "(...)"), split the string based on that pattern, again removing empty elements, and store those into four variables representing the four faces. Those are then string concatenated onto h through k.
The next line then ships h through k through the function to output the sides (left, front, right, back) of the cube.
Finally, we run the last $n lines through the function to output the bottom face of the cube.
All of the numbers are left on the pipeline, and output is implicit.

APL (Dyalog Classic), 30 27 bytes
{+/⍎¨6(⍺*2)⍴⍉⊃,⌿3⍺⍴⍵⊂⍨⍵∊⎕D}

Shaved off 3 bytes thanks to @Adám
⍺ is n
⍵ is c
Explanation
                        ⍵⊂⍨⍵∊⎕D   c partitioned by ⎕D (digits 0..9)
                    3⍺⍴           reshape into 3 by n matrix
                 ,⌿              concatenate on first axis (results in n vectors)
              ⍉⊃                  ravel transpose mix (results in a simple string with all digits in side order)
      6(⍺*2)⍴                     reshape into 6 by n squared matrix (one row per side)
 +/⍎¨                            sum rows execute each (execute will turn characters into numbers)

Try it online!

Looks like 59 bytes to me. Replacing ⊆ with ⎕U2286 will only add 5 bytes though.

My bad, I was playing with and without partitioned enclose and only used the byte count for Classic version. Will edit my answer to use migration level 3 :)

I just specify that it needs ⎕ML←3 which is default on many systems.

Also, you can remove the space between 3 and ⍺.

(6,⍺*2) → 6(⍺*2)

IFAICT, you don't need , after ⍴ as ⍴ always uses its right argument in ravel order.

Haskell, 128 bytes
s n c=filter(>=0)$map(\[x,y]->sum$map(\[v,w]->fromEnum((lines c)!!(x*n+v)!!(y*n+w))-48)$n%n)$3%4
n%m=sequence[[0..n-1],[0..m-1]]

Accepts a string with line breaks.

Cubically, 19 bytes
r%0@%1@%2@%3@%4@%5@

Takes the cube from STDIN and the size as a command-line argument to the interpreter. Outputs the sum of the top face, a null byte, the left face, a null byte, ... the bottom face, and a null byte.
Try it online! ...which apparently displays null bytes as some sort of whitespace on my browser.

Try it online! (4x4x4)
Try it online! (5x5x5)

This language wasn't made for this challenge, but the challenge was made for the language.... is it still cheating? ;)


text:
Divisible by 1000003? Easy, just multiply the last digit by 300001 and add!
Given a prime P greater than 10, your program or function must figure out its divisibility rule x, defined as the integer with smallest absolute value which yields a multiple of the original prime when multiplied by the last digit of the prime and added to the rest of the original prime.
Example
Given an input 31, the last digit is 1 and the rest of the number is 3. Thus your program must find the integer x with minimum absolute value such that 1*x + 3 is a multiple of 31. In this case, x=-3 works, so the program or function would return -3.
Given an input 1000003, the last digit is 3 and the rest of the number is 100000. Thus your program would find x=300001 because 3*300001+100000 = 1000003 which is a multiple of 1000003.
Mathematical Background
The value of x can be used as a divisibility test. If a number N is divisible by P, then adding x times the last digit of N to the rest of N will yield a multiple of P if and only if N is divisible by P in the first place.
For P=11, we get x=-1, which is equivalent to the well-known divisibility rule for 11: a number is divisible by 11 alternating difference of its digits is divisible by 11.
Rules

The output may be in any form that clearly encodes both the sign and value of the output.
The input prime will be between 10 and 2^30.
You do not need to handle if the input is not a prime or is not in the range.
You do not need to handle if both x and -x are valid outputs (should not happen).
Brute force is permitted, but more creative solutions are appreciated.
This is code-golf, so shortest code in each language wins! Do not let answers in golfing languages discourage you from posting in other languages.

Test Cases
Input   Output
11  -1
13  4
17  -5
19  2
23  7
29  3
31  -3
37  -11
41  -4
43  13
47  -14
53  16
59  6
61  -6
67  -20
71  -7
73  22
79  8
83  25
89  9
97  -29
101 -10
103 31
107 -32
109 11
113 34
127 -38
131 -13
1000003 300001
2000003 600001
2999999 300000
9999991 -999999

A useful simplification: we're looking for the smallest x in absolute value where 10*x-1 is divisible by the input.

Can anybody provide a hint why (3 / (n % 5 * 2 - 5) * n + 1) / 10 and (n % 5 * 2 - 5^2) * n / 10 + 1 are able to find a minimal absolute value for something like this? My first intuition would have been to calculate the least common multiple using the greatest common divisor calculated with Euclid's algorithm.

@DavidFoerster Given a number, you can remove the last digit, multiply it by a number x, add it on, and still get a number divisible by n. If we then multiply the new number by 10 and subtract the original number it still remains divisible by n. xnor's comment then follows from some algebra. The next step is to rearrange the formula so that it gives x in terms of n: x = (k*n+1)/10. We want the smallest absolute x so therefore we want the smallest absolute k, and this must be whichever one of -3, -1, 1 or 3 (depending on n's last digit) that makes the division exact.

JavaScript (ES6), 32 25 23 bytes

f=
n=>(3/(n%5*2-5)*n+1)/10
<input type=number min=1 oninput=o.textContent=this.value%5*(this.value%2)?f(this.value):``><pre id=o>

3/(n%5*2-5) would be written 9/n(mod -10) if I had access to balanced modulo division. Edit: Saved 2 bytes thanks to @EgorSkriptunoff

You can save 2 bytes by replacing n=>((n%10*2%14-3)*n+1)/10 with n=>(3/(n%5*2-5)*n+1)/10

This is a polyglot for .Net C#.

@KevinCruijssen Probably a near-miss polyglot for Java 8 too... oh wait, I see your answer now!

@Neil You're right. I usually post Java answers, so I was already working on a port of xnor when I saw your answer. Posted it either way as a boring port crediting you.

Python 2, 27 bytes
lambda n:(n%5*2-5^2)*n/10+1

Try it online!
The operations are done left to right:  (((n%5)*2)-5)^2.
I used my arithmetic brute forcer to find the expression n%5*2-5^2 to perform {1:-1,3:3,2:-3,4:1}[k], taking the negative inverse of a residue mod 5 into the range [-2..2].

Is this arithmetic brute forcer publicly available somewhere?

Is that the only expression it found or does it just print the first one of a given length? (3/(n%5*2-5) is the same length as (n%5*2-5^2).)

@Lynn No, I might clean and up and post it when I have time.

@Neil It only found equivalents and n%5*2-6^3. I only looked up to the length though of the expression without parens, whereas 3/(n%5*2-5) is two characters longer but saves on outer parens due to precedence. Searching expressions of this length should take a while. This use-case does suggest an option to only find expressions that can be used in a given context via their outermost operation having high enough precedence.

Jelly, 10 8 bytes
,N⁵æiAÞḢ

Try it online!
Explanations
,N       Get [Input, -Input].
⁵æi      Modular inverse of 10 mod each of [Input, -Input].
AÞ       Sort by absolute value.
Ḣ        First.

+1 I have never seen a Jelly submission with register that actually saves bytes

@Mr.Xcoder It was because I didn't golf it well.

Brachylog, 14 bytes
∧.ℤ≜×₁₀-₁;?%0∧

Try it online!

Japt, 16 9 bytes
Saved way too many bytes thanks to an observation by @xnor
_*AÉ vU}c

Test it online! May take a couple of seconds on larger inputs.
Explanation
_  *AÉ  vU}c    Implicit: U = input integer
Z{Z*A-1 vU}c    Ungolfed
Z{        }c    Loop through each integer Z in [0, -1, 1, -2, ...] and yield the first where
  Z*A             Z times 10
     -1           minus 1
        vU        is divisible by the input.
                Implicit: output result of last expression

Python 2, 69 54 53 bytes
Edit: -15 bytes thanks to @Mr.Xcoder
Edit: -1 byte by using recursion
f=lambda a,x=-1:(a%10*x+a/10)%a and f(a,-x-(x>0))or x

Try it online!

54 bytes. I don't see why you have those variables when you only use them once

Yeah, was in a bit of a hurry when I wrote it

Python 2, 31 29 27 bytes
lambda n:3/(n%5*2-5)*n/10+1

Try it online!

Java 8, 23 21 bytes
n->3/(n%5*2-5)*++n/10

Port of @Neil's JavaScript (ES6) answer, but -2 bytes thanks to @Nevay due to implicit flooring of integers.
Try it here.

21 bytes: n->3/(n%5*2-5)*++n/10

@Nevay Even when I create a port of the top answer, you still have to golf me.. xD (Read: Thanks and nice job!)

Excel, 25 bytes
=.3/(MOD(A1,5)*2-5)*A1+.1

(Excel corrects to:
=0.3/(MOD(A1,5)*2-5)*A1+0.1

)

Actually I think you're allowed to claim the number of bytes you need to enter (but I'm too lazy to check meta).

@Neil yes - you are allowed to claim the number of bytes entered for google sheets, excel, and vba

Japt, 14 bytes
Inspired by Neil's solution.
Ì*2%E-3 *UÄ /A

Test it online!
Explanation:
  Ì  *2%E-3 *UÄ  /A
((UgJ*2%E-3)*U+1)/A
  U                  // Implicit U = Input
   gJ                // Get the char at index -1 (last char)
     *2              // Multiply by 2
       %E            // Mod 14
         -3          // Minus 3
            *U+1     // Multiply by U+1
                 /A  // Divided by 10

Pyke, 12 bytes
3Q5%}5-f*hTf

Try it here!

Pyth, 14 bytes
h/*x-y%QK5K2QT

Try it here.

Pyke, 10 bytes
~IIT*tR%)h

Try it here!
~I         -   Integers
  I     )  -  filter(^, not v)
   T*t     -    ^ *10 -1
      R%   -   input % ^
         h - ^[0]

Python 2, 44 43 bytes
(Crossed out 44 is still 44.) Thanks to Fireflame241 for saving a byte!
P=input();i=P/3
while i*10%P-1:i-=1
print i

Try it online!
There is exactly one number between 0 and P-1 which is an inverse of 10.  But if that inverse u happens to be greater than P/2, then (u-P) is also an inverse, and has a smaller absolute value than u.  So it turns out that we're really looking for the unique number x between -P/2 and P/2 which is an inverse of 10.
The code above does exactly that, starting at (the floor of) P/2, and stepping
downward until an inverse is reached.  This must happen for some number greater than -P/2 so long as P is a prime greater than 10.  More precisely, it will terminate if and only if P is coprime to 10.
Edit: It actually turns out that x is guaranteed to be between -P/3 and P/3, so the current version starts at P/3 and steps down from there.  See the section labeled Improved Bound for an explanation of this.
Mathematical explanation
It was not immediately obvious to me why the divisibility test worked.  Here's an explanation, in case anyone else was wondering.
Let P be a prime, greater than 10, whose last digit is b.  Thus
P = 10a + b
where a > 0, and 0 <= b < 10.  In fact b is either 1, 3, 7, or 9, because a prime greater than 10 must end in one of these digits.
Now suppose bx + a = 0 (mod P).  Then
a = -bx (mod P)
10a + b = 10(-bx) + b (mod P)
0 = 10(-bx) + b (mod P)
0 = b(1 - 10x) (mod P)
Since P is prime, the integers mod P are an integral domain. So  either b = 0 (mod P), or 1 - 10x = 0 (mod P).
We know 0 <= b < 10 < P, so if b = 0 (mod P) then b = 0.  But we said b is either 1, 3, 7, or 9, so this is impossible.  Therefore 1 - 10x = 0 (mod P), so 10x = 1 (mod P).  In other words, x is the inverse of 10, modulo P.
Now suppose N is a nonnegative integer whose last digit is d, so N = 10c + d.  We have a chain of equivalent statements:
10c + d = 0 (mod P)
<==> 10xc + dx = 0 (mod P)
<==> c + dx = 0 (mod P)
QED.
Usefulness?
I was also wondering whether the divisibility test (given N = 10c + d, replace N by dx + c) would actually be productive in practice.  Or at least, does it reliably replace N by a number smaller than N (in absolute value)?
Suppose N = 10c + d, where c >= 0 and 0 <= d < 10.  Therefore 10c = N - d <= N.  By the triangle inequality,
|c + dx| <= |c| + |dx| = c + d|x| <= N/10 + d|x|
< N/10 + 10|x| <= N/10 + 10P/2 = N/10 + 5P
Thus if 5P <= 9N/10, then |c + dx| < N.
In particular, if N >= 6P, then |c + dx| < N.  Thus, given P we begin by calculating 2P, 3P, ..., 6P, along with x.  Then given N, we run the divisibility test repeatedly until we reach a number less than or equal to 6P, and check whether the result is any of the numbers 0, P, 2P, ..., 6P.
(Of course, whenever we reach a negative number, we replace it by its absolute value, which is fine since q is divisible by P if and only if (-q) is.)
Improved Bound
I noticed that |x|/P never seemed to be close to 1/2.  In fact it seemed like it was always less than 1/3...or upon closer examination, it was always very close to either 1/10 or 3/10.  The biggest it ever got seemed to be 4/13 (which happens when P=13 and x=4).  Why would this be?
Let u be an integer and suppose that 10u = kP + 1 for some integer k, so u is an inverse of 10, modulo P.  Then we also know that k is relatively prime to 10, since k(-P) is equivalent to 1 modulo 10.
Now, we know that the inverses of 10 modulo P all differ by multiples of P, so we can take the integer u and either add or subtract multiples of P at will, and the result will always still be an inverse of 10 modulo P.  Suppose we choose to subtract P from u: we get
10(u - P) = 10u - 10P = kP + 1 - 10P
10(u - P) = (k - 10)P + 1
In other words, decreasing (respectively, increasing) u by P corresponds to decreasing (increasing) k by 10.  We wish to add/subtract multiples of P from u until the left-hand side is minimized in absolute value; but the left-hand side is minimized exactly when the right-hand side is minimized, and so we want to add/subtract 10 from k until the right-hand side is minimized in absolute value.
But we know that this will happen when k is between -5 and 5, and therefore (since k is relatively prime to 10) this means k is either -3, -1, 1, or 3.  (This is the content of @Neil's comment under the OP. Thanks, Neil!)
Thus when |u| is minimized (i.e., u=x), we'll have x/P = u/P = k/10 + 1/(10P), where k is either -3, -1, 1, or 3.  Therefore |x|/P <= 3/10 + 1/(10P).  Equivalently, |x| <= (3P + 1)/10.
Further, this inequality is strict at P=11, because at P=11 we have x=-1 and k=-1.  The smallest P for which equality holds is P=13 (where x=4 and k=3).
Therefore the largest that |x|/P ever gets is 3/10 + 1/(10*13), because P=13 is the first prime for which we have k=3, and among those with k=3, the 1/(10P) term is largest when P is smallest (i.e., at P=13).  Therefore, for all P, we also have |x|/P <= 3/10 + 1/130 = 4/13 < 1/3.  This explains why in the above code we can initialize at i = P/3 rather than having to start at P/2.
Further, the bounds in the Usefulness section above can now be improved.
Lemma: Let N = 10c + d where c > 0 and 0 <= d <= 9.  Then c + d|x| < N/10 + 9(3P + 1)/10.  (Note the strict inequality.)
Proof of Lemma: by cases.  Case I: d = 0, so N = 10c.  Then c + d|x| = c = N/10 < N/10 + 9(3P + 1)/10.
Case II: 0 < d <= 9.  Then 10c = N - d < N, so c < N/10.  Therefore c + d|x| < N/10 + d|x| <= N/10 + 9|x| <= N/10 + 9(3P + 1)/10. QED.
Thus, if N > 3P (and N = 10c + d as before), then
3P + 1 <= N
9(3P + 1)/10 <= 9N/10
N/10 + 9(3P + 1)/10 <= N
c + d|x| < N/10 + 9(3P + 1)/10 <= N
So, if N > 3P then c + d|x| < N.
Therefore, we only have to find P, 2P and 3P, along with x.  Given N > 0, while N > 3P, we replace N by |c + dx|, which decreases N. Eventually we'll get N <= 3P; at that point we stop and check whether N is equal to any of the numbers 0, P, 2P, or 3P.
We can't do better than 3P in general. For example suppose P = 13 and N = 39, so x = 4. Then replacing N by dx + c = 9(4) + 3 leaves N unchanged.

Very nice explanation! You can save a byte by moving -1 outside the parenthesis:  43 bytes

@fireflame241 Thank you very much!  I could claim that I left it at 44 just so I could cross it out (though this would be a lie).

Whitespace, 92 bytes
Note that this language's syntax consists of only whitespace, so each whitespace character has been prefixed here with S, T, or L (corresponding to Space, Tab, and Linefeed, respectively). These can be removed without losing functionality, but they are included here in order to display it correctly.
S S S L
T   L
T   T   S S S L
T   T   T   S L
S S S S T   T   L
T   S S L
S L
T   S S S T S T L
T   S T T   S L
S T S S S S S S T   S T L
T   S S T   T   S T S S S S T   L
T   S S S S S S T   S T S L
T   S T S T L
S T L
L
L
.

Try it online!

Husk, 10 bytes
ḟȯ¦⁰←*10İ±

Try it online! A port of ETHproductions' answer.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Turn an integer n into a list containing it n times
Given an integer n as input, return a list containing n, repeated n times. For example, the program would take 5 and turn it into [5,5,5,5,5]. The elements need to be integers, not strings. No built-in functions that accomplish the task are allowed.
This is code-golf, so standard rules apply.

Why no builtins?

@Okx I meant built-in functions which already do this, must have used the wrong word, i'll edit the post.

I edited the question such that it is a bit more readable and fits our standard format better.

Should n=0 be supported?

@BrunoE That still doesn’t answer the why. Do you have an actual reason to ban built-ins? To quote xnor: In general, if your challenge is too simple to be interesting, it won't be saved by banning things.

Related.

With your current prohibition on built-ins, is this valid?

Does it matter? This is meant to be fun, we can have different opinions on what is and isn't valid.

@BrunoE while I agree with the sentiment, we prefer objectivity here at ppcg. Either something is or is not valid, opinions shouldn't come into the equation.

@BrunoE The specs must be made such that one can indisputably decide whether an entry is valid or not. Please share your thoughts on the existing answers and make the specs more objective when it comes to built-in.

in which case, I'll (begrudgingly) say the entry is invalid.

@Lynn then let the challenge be considered 'uninsteresting'. Nobody is under any obligation to answer, but a fair number of people seem to have found it interesting enough.

Along with @Arnauld's comment, can we assume the input is non-negative?

I'm still confused what counts as a "built-in" for this task. Is Python's * operator ok? What's an example of a built-in that isn't ok?

I am suprised nobody has mentioned this yet, but we have a sandbox for challenges where you can post them to get feedback on them, before they go live. This way you might've prevented discussing the rules of the challenge while others already submitted their answers.

Can we leave the output on the stack for stack based languages, or do we have to print it?

Jelly, 1 byte
x

Try it online!
Note that this is not the “repeat n n times” built-in — its function is more general than that. For example 4,5,6x1,2,3 equals [4, 5, 5, 6, 6, 6]. Given only one argument, Jelly just happens to use it as both the left and right argument for the supplied link, but this functionality is not inherent to x.
If this doesn’t count, there are various fun 2-byte alternatives:
x` ṁ` Ra Rị R» a€ oR oḶ oṬ oẊ Ḷị Ḷ» Ṭị Ṭ» Ẋị Ẋ» ị€ ṛ€ ȧ€ »€

etc.

No built-in functions that accomplish the task are allowed. While x may be more general, it is indeed a built-in function that accomplishes the task.

Well, yes. Every code golf answer is a collection of built-ins that accomplish the task. You might ban this answer if x did “all the work”, but it most certainly doesn’t — there’s an implicit “0 bytes” of link-parsing and array-coercion logic going on to turn this into repeat([n], n), which is exactly what other answers do.

@Mr.Xcoder Who cares about intention? x is a built-in function. x accomplishes the task. No built-in function that accomplish the task are allowed. Therefore, x is not allowed.

@Lynn The fact that that is Jelly's normal way of treating missing arguments is exactly what makes x prohibited. APL's / (the grandfather of Jelly's x) and J's # (the father of Jelly's x) are not prohibited because they need ⍨ and ~ respectively to explicitly use the input as both count and data.

@Adám I think the difference lies in that this is not the function of the x command. When used in different cases, it provides different effects; it's no different than a J or APL answer with an implicit ~ or similar at the end of the program.

@ConorO'Brien But it is. A complete documentation for x would have read when applied to one or more numbers, it returns a list where each element Xₙ is expanded to Xₙ copies of itself.

@Adám This is the "repeat each element of x y times" function, taking 2 arguments. What makes it accomplish the task is how Jelly parses implicit arguments, which has nothing to do with the function itself.

If this answer is invalid then the constraint of the question is not "No builtins" it is "No 1 byte answers", which is an extremely arbitrary limitation that seems counterproductive in code golf.

I think an argument towards this not being a built-in is that there are two other 1 byte answers in Jelly that do the same thing ṁ and ẋ so this answer could be any one of the three.  There aren't 3 built-ins (one would hope) for "repeat n n times", so they can't ALL be a "built-in" for it.

@nmjcman101 I disagree. In my APL answer you see three built-ins that almost do the task; they just need to be told to use a single argument twice. This "telling" is built into Jelly. Whether you call it part of its primitives or part of the language is just a matter of semantics. All three are Jelly built-ins for the exact job. Compare to multiplication and minimum on Booleans. Wouldn't both be prohibited in a challenge to AND two Booleans without built-ins for the exact task?

@Adám I would say that multiplication and minimum are not builtins for boolean AND, even if they complete a challenge which requested boolean AND. Perhaps this should be made a meta-post for further discussion?

@KamilDrakari K has a single built-in & labelled min|and.

@Adám I've posted this meta post for further discussion on this topic.

This whole comment thread seems a good argument for not banning something as subjective as builtins.

Python 3, 14 bytes
lambda k:[k]*k

Try it online!

What's wrong with just [n]*n?

@paxdiablo That is a snippet. We can create either full programs or functions as per the meta consensus.

Operation Flashpoint scripting language,  50  46 bytes
f={a=[];t=_this;while{count a<t}do{a=a+[t]};a}

Call with:
hint format["%1", 5 call f]

Output:

Do you have post decrement, i--, and += in this?

@TheLethalCoder Unfortunately, no.

Why are the screenshots for this always in a barren desert? You should use a cool map for your screenshots :P.

@MagicOctopusUrn Is that better?

@Steadybox ahaha! Epic :P. Is that the town from left for dead? That looks like the church you start in kinda.

@MagicOctopusUrn No, it's just a town from one of the game's original maps.

I always upvote OPFP

I think the screenshots should be posted cropped to a smaller image. We don't need to see the map, and it distracts from the actual output.

APL (Dyalog), 2 bytes
Five equally short solutions. Last two are courtesy of Zacharý.

⍴⍨

Try it online!
⍴ cyclically reshape
⍨ self

/⍨

Try it online!
/ replicate
⍨ self

\⍨

Try it online!
\ expand
⍨ self

⌿⍨

Try it online!
⌿ replicate along first (and only) axis
⍨ self

⍀⍨

⍀ expand along first (and only) axis
⍨ self
Try it online!

@Uriel There's one more…

Both ⌿⍨ and ⍀⍨ work.

Was it intentional that 'self' looks like a face?

@geokavel I don't think so, but I also noticed it as a typed this post. Makes it pretty mnemonic, no? In fact, selfie is one of its semi-official names, so in the RIDE interface to Dyalog APL, you can insert ⍨ by typing ``selfie.

⍀ and ⍨ are each three-byte characters. TIO does report the bytesize correctly. I feel like you should know this.

@sethrin TIO counts characters (and UTF-8 bytes where applicable), but it is up to the user to ensure that they do not use any characters that are missing from a single-byte character set (SBCS). For APLs, see here.

@Adám thanks for the correction. I'll have to read more about APL's charset.

Mathematica, 10 bytes
#~Table~#&

Proton, 8 bytes
n=>[n]*n

Try it online!

This combines the best of the python answer and the javascript answer, I love it!

JavaScript (ES6), 19 bytes
n=>Array(n).fill(n)

Try it

o.innerText=(f=
n=>Array(n).fill(n)
)(i.value=8);oninput=_=>o.innerText=f(+i.value)
<input id=i type=number><pre id=o>

An array without ... - whatever next?!

@Neil: it felt wrong even as I was typing it! :D

Octave, 12 bytes
@(n)~(1:n)+n

Try it online!

What does the ~ in octave, because that's the only part of your code I don't understand..

@Michthan Sorry for late reply. ~ is the  not operator that converts 1:n to an array of  0s of size n. You can use ! instead of it.

Pyth, 2 bytes
*]

Test suite.

*]QQ - Full program with implicit input

 ]   - Turn the input into a list.
*    - Repeat it a number of times equal to the input.

Haskell, 13 bytes
f n=n<$[1..n]

Try it online! Usage: f 5 yields [5,5,5,5,5]. For n=5, [1..n] yields the list [1,2,3,4,5]. n<$ replaces each element of this list with n.

Mine's a bit longer, but I like it anyway: join replicate

@amalloy This would indeed be the clean Haskell way to do it. However, join is not part of Prelude and thus requiers a lengthy import Control.Monad, which rarely makes it useful for golfing.

R, 18 bytes
array(n<-scan(),n)

Try it online!

Is rep(n<-scan(),n) too close to a builtin?

@RobinGertenbach Maybe you should post it as a separate answer.

05AB1E, 2 bytes
Fˆ

Try it online!

Nice, better than .D).

@MagicOctopusUrn: Yeah, that was my first thought.

Dodos, 76 bytes
	f f r 2
2

r
	r d
	f s t f
d
	dip f s t
	f
t
	dot f
	dot
s
	s dip
f
	dab

Try it online!
Explanation:
f is an alias for dab (tail).
s is subtraction, as explained on the wiki: (x, y) → (0, y−x) when x ≤ y.
t maps (a, b, c…) to (b+c+…, a+b+c+…).
f s t maps (a, b, c…) to a. This is our “head” function.
d dips only the head of its argument: (a, b, c…) → (|a−1|, b, c…)
r is the main repetition logic. We map (a, b) to (*r(|a−1|, b), b).
For example, r(4, 7) will evaluate as
  r(4, 7)
= r(3, 7), 7
= r(2, 7), 7, 7
= r(1, 7), 7, 7, 7
= r(0, 7), 7, 7, 7, 7
  → This would call r(1, 7), but (1, 7) ≥ (0, 7), so surrender!
= 0, 7, 7, 7, 7, 7.

Finally, we define 2, which maps n → (n, n), and define main as f f r 2, computing r(n, n) and chopping off the first two elements.

Japt, 2 bytes
ÆU

Test it

Explanation
Implicit input of integer U. Generate an array of integers from 0 to U-1. Fill it with U. Implicit output of resulting array.

Perl 5, 18 14 bytes
-4 bytes thanks to @DomHastings
sub{(@_)x"@_"}

Try it online!
Is x a builtin that does the entire task? Sort of? Not really? Rules unclear?
Edit: Yeah, probably it's fine.

Had pretty much the same, but you can change the first $_[0] to @_! Also the second can be"@_" I think...

I would say it doesn't count as a built-in because you have to work around the fact that it takes two inputs instead of one.

Why not $_=$_ x$_ with perl -pe?

@Thor x does string repetition, not list repetition, unless the left operand is in parentheses (or is a qw operator) and the x is evaluated in list context.  And of course $_ is a scalar, not a list.

I meant something like this: echo 5 | perl -pe '$_=$_ x$_'

@Thor I wouldn't count that as satisfying "return a list".

Java (OpenJDK 8), 50 48 bytes
n->java.util.Arrays.stream(new int[n]).map(i->n)

Try it online!
-2 bytes thanks to @Jakob
Inspired by the comments in @OlivierGrégoire's post, and optimized a little further. Takes an integer input, creates an IntStream of n elements, then maps each element to n and returns it.

You can save 2 bytes by starting with java.util.Arrays.stream(new int[n]).

Haskell (14 bytes)
replicate>>=id

Thanks to @nimi, I don't need any import anymore. Yay!
It's a function that takes an integer argument; for example, the following returns [5,5,5,5,5]:
(replicate>>=id) 5

Why not id=<<replicate? It's also 14 bytes but doesn't need the import.

@nimi Very good point! Overlooked that possibility. (I really need to dive into the arrow monad more...)

TeX, 81 bytes
\newcommand{\f}[1]{#1\count0=2\loop,#1\advance\count0 by1\ifnum\count0<#1\repeat}

Usage
\documentclass[12pt,a4paper]{article}
\begin{document}
\newcommand{\f}[1]{#1\count0=2\loop,#1\advance\count0 by1\ifnum\count0<#1\repeat}

\f{5}

\f{10}
\end{document}

That's actually LaTeX. In Tex it'd be much shorter.

Husk, 2 bytes
´R

Try it online!
´    -- Apply next function twice to same argument
 R   -- given an integer n and some element, replicate the element n-times

Polite alternative (3 bytes)
ṠIR

Try it online!

J, 2 bytes
$~

Same as the APL answer: reflexively shape the input. In other words:
$~ y
y $ y
NB. y copies of y

Brainbash, 39 bytes
>-[-[-<]>>+<]>->#[->+>+<<]>>[-<;<<.>>>]

Try it online!
Prints N N times. Works by generating 32, taking input, then duplicating the input twice, then output the first for each 1 in the second.

C (gcc), 55 bytes
int*f(k){int*r=malloc(k*4),a=k;for(;a-->0;)r[a]=k;k=r;}

Try it online!
Returns a list of k integers.

Yay "long arrow operator". Also, I didn't think gcc would ever use register eax for locals. Go figure.

You can save 2 bytes by removing a comparison to 0 in for cycle, unless I've overlooked something.

Suggest *f(k){int r[k], instead of int*f(k){int*r=malloc(k*4),

Röda, 10 bytes
{[[_]*_1]}

Try it online!
Explanation:
{[[_]*_1]}
{        } /* Anonymous function   */
   _       /* The input (_1)       */
  [ ]      /* As a list            */
     *_1   /* Repeated _1 times    */
 [      ]  /* Pushed to the stream */

Why can you leave off the 1 in the first input but not the second?

@ConorO'Brien Each underscore without a number has a number that is one larger than the previous: [_]*_ = [_1]*_2. Because the first underscore is the first, it has automatically the number 1.

Coreutils, sed, 14 bytes
yes $1|sed $1q

As a zsh function, 20 19 bytes:
f(){yes $1|sed $1q}

Try it online!

I don't think this answer is valid, since it doesn't take input.

@DJMcMayhem: used it in a function

Why not just make it a program yes $1|sed $1q?

Good point @DigitalTrauma, updated

The rules say it has to be integer elements, not string elements.  To satisfy that, a bash/zsh answer would need to use declare -i integer variables.  But it also has to be an array.  I'm not sure bash even supports an integer array (like eval declare -ia "$1" to use the first function arg as the name of an array return value.)  I upvoted this because it follows the spirit of the question; I doubt the question meant to exclude languages that don't really have integer lists / arrays.

MATL, 4 3 bytes
tY"

Try it online!
Explanation:
t       % duplicate elements
Y"      % replicate elements of array
        % (implicit) convert to string and display

Groovy, 9 bytes
{[it]*it}

Try it online!

Perhaps the most competitive groovy answer I've done to date.

brainfuck, 16 bytes
[->+>+<<]>[->.<]

Try it online!
The breakdown:
[->+>+<<]          Duplicate 'n' into the next 2 cells to the right
         >         Move to the first duplicate
          [->.<]   Print 'n', 'n' times

As I'm sure you're aware,  brainfuck takes input and output values as ASCII characters. So a ! is represented as the value 33.

Your program doesn't take input, I don't think. Unless you're talking about a value left on the tape

@ConorO'Brien The ladder. Think of it as a function more than a program.

Java (OpenJDK 8), 58 56 bytes
n->{int a[]=new int[n],i=n;for(;i-->0;)a[i]=n;return a;}

Try it online!
-2 bytes thanks to @KevinCruijssen

Two bytes shorter: n->{int a[]=new int[n],i=n;for(;i-->0;)a[i]=n;return a;}

@KevinCruijssen Ouch, it hurts I didn't think about that... Thanks!

Happens to the best of us. ;) If you look in my answer history you'll probably also find some answers where I add something along the lines of "bytes saved thanks to ... due to a stupid mistake by myself / something obvious I forgot.." :)

I thought about an answer like IntStream.generate(() -> n).limit(n) but decided it wasn't worth typing up and upvoted this instead :)

@JollyJoker You could do it! It's indeed two bytes shorter and would easily beat my answer ;-)

Yeah, but it's also flat out the canonical correct way of doing that in Java 8 so it's a pretty boring answer

Isn't using Arrays.fill(a,n)wouldn't be shorter than looping? (I'm new to PPCG, don't know if java.util can be used).

@Jean-BaptisteYunès If you want to try that, compare the two following: i=n;for(;i-->0;)a[i]=n; and java.util.Arrays.fill(a); (yes, the full name is required). 23 bytes vs. 25 bytes. I think I'll keep the loop. But thanks anyways ;-)

Ok I was not aware about full name qualification. I tried to find the rules but wasn't able? Any hint please?

@Jean-BaptisteYunès Here are a few links to allow you to start getting around here: https://codegolf.stackexchange.com/tags/code-golf/info https://codegolf.stackexchange.com/questions/6671/tips-for-golfing-in-java https://codegolf.meta.stackexchange.com/questions/tagged/code-golf And specifically about imports: https://codegolf.meta.stackexchange.com/questions/8287/on-scoring-imported-functions

Swift 3, 29 bytes
{n in(0..<n).map{_ in n}}

Try it here!
Swift 3, 30 bytes
{Array(repeating:$0,count:$0)}

Try it here!

I wonder if we can get the input as the same variable repeated twice. Then you could have a 10 byte solution: Array.init. Just assign it to a variable with a type alias, and boom: let f: (Int, Int) -> [Int] = Array.init; print(f(5, 5))

@Alexander No, we cannot get the input twice.

C# (Mono), 38 37 bytes
n=>System.Linq.Enumerable.Repeat(n,n)

Old version for 38 bytes:
n=>"".PadLeft(n,(char)n).ToCharArray()

Try it online!
A char in C# is an int underneath so this appears to be valid.

C# (Mono), 44 bytes
using System.Linq;n=>new int[n].Select(_=>n)

If the above is invalid this is for an extra 6 bytes.
Try it online!

Also 38 Bytes but more readable:
n=>new String((char)n,n).ToCharArray()

@TheJoeIaut So you're aware that would have to be new string... note the lower case :) Though yes it is the same length unfortunately.

25: n=>Enumerable.Repeat(n,n)

@ManfredRadlwimmer Actually 37 but does save a byte thanks!

Oh, right - the using

@ManfredRadlwimmer Well you can fully qualify it here :)

Tampio, 109 85 bytes
a:n uni on a a:na
nolla a:na on tyhjyys
a:n seuraaja o:na on o lisättynä a:han o:na

Explanation:
a:n uni on   a a:na
uni(a)  =  f(a,a)

  nolla a:na on tyhjyys
f(0,    a)   =  []

  a:n seuraaja o:na on o lisättynä a:han o:na
f(a   +1,      o)   =  o :       f(a,    o)

uni(a)   = f(a,a)
f(0  ,a) = []
f(a+1,o) = o : f(a,o)

PHP, 19 Bytes
I'm new here can anyone tell if this is ok ?
for(;$b--;)$a[]=$n;

try it online!
EDIT:
looks to not be a valid form so :
32 Bytes (by Titus)
(+1 Byte for R flag)
for($b=$argn;$b--;)echo$argn,_;

try it online!

Use Try It Online: https://tio.run/#php

@Nnnes it's better like this ?

Wellcome to PPGC. You need to use some form of input and output you're not allowed to handle that outside. Use e.g. $_GET, $argv, $argn or read from stdin. for($a=$argn;$argn--;)$b[]=$a;echo implode(',',$b); would work. echo$a=$argn;for(;--$argn;)echo',',$a; would be better though ;) You would be allowed to submit a function but they are usally longer in php :/

function a($b){for($n=$b;$b--;)$a[]=$n;return$a;} would be valid for example.

... or for($b=$argn;$b--;)echo$argn,_; (and don´t forget to count +1 for the R flag)

@Titus i don't get it about the $argn and the flag, i understand that you do it by command line but i don't find a way to use input for command on tio.run (feel free to edit if it's necessary)

afaik, TiO cannot handle $argn. Just define a variable with that name in the header.

cQuents v0, 3 bytes
::n

Try it online!
Explanation
::    Mode: sequence 2. Given input n, output the sequence n times
  n   Each item in the sequence is n

Note current version uses & instead of ::

Common Lisp, 31 bytes
(lambda(x)(fill(make-list x)x))

Try it online!

Perl 6, 9 bytes
{$_ xx$_}

Try it online
Uses the built-in list/statement repeat operator xx

Kotlin, 22 bytes
{n:Int->(1..n).map{n}}

Try it online!

Welcome to the site! :)

Element, 9 bytes
_2:'[2:`]

Try it online!
_        input
2:       double the input
'        push one to control stack
[2:`]    for (number), double it, output one of them

Ruby, 10 characters
->n{[n]*n}

Sample run:
irb(main):001:0> ->n{[n]*n}[5]
=> [5, 5, 5, 5, 5]

Try it online!
Ruby, 18 characters
->n{Array.new n,n}

Sample run:
irb(main):001:0> ->n{Array.new n,n}[5]
=> [5, 5, 5, 5, 5]

Try it online!

PowerShell, 13 10 bytes
{@($_)*$_}

Usage
PS C:\> 2 | % {@($_)*$_}
2
2

And:
PS C:\> 5 | % {@($_)*$_}
5
5
5
5
5

By default, PowerShell shows array content one element per line. Running it through the ConvertTo-Json cmdlet shows it in a more familiar form:
PS C:\> 5 | % {@($_)*$_} | ConvertTo-Json -Compress
[5,5,5,5,5]

Can you call this with 5 | % {@($_)*$_}?  If so you don't need the 3 bytes ($f=) required to name the function.

Yes it can. Thanks!

TI Basic, 6 bytes
Ans+0rand(Ans

Thanks to @Oki for this solution!

0 can be replaced with lots of things (int(/iPart(, imag(, angle(, ...). Alternative solution: Ansnot(not(rand(Ans. Other noteworthy solutions  (1 byte longer) randInt(Ans,Ans,Ans, Ansrand(Ans)^0, Ans(1^rand(Ans, -Ansint(-rand(Ans

TI Basic, 10 bytes
This assumes an empty list
Ans→dim(L₁:L₁+Ans

Here's the hex, along with the code to explain the byte count:
72  04 B5   5D 00 3E 5D 00 70 71
Ans →  dim( L₁    :  L₁    +  Ans

How?
Ans→dim(L₁:L₁+Ans
Ans→dim(L₁        Since the list is empty, this makes L₁ a list on Ans 0's
          :       Separator
           L₁+Ans Since TI-Basic vectorizes some commands,
                  this adds Ans (basically the input here) to each element in L₁,
                  which results in Ans for each element.

Ans+0rand(Ans for 5 bytes

Thanks, I'll post that in another solution, since it's pretty different!

Actually, that's six bytes, rand( isn't a thing. It's Ans + 0 rand ( Ans.

You're right. Instincts..

Also should mention that on newer calculators (CSE?) you can use ceiling() to save a byte

Flurry, 12 bytes
({}){({})}{}

Run example
$ ./flurry -inn -c "({}){({})}{}" 3
3 3 3
$ ./flurry -inn -c "({}){({})}{}" 6
6 6 6 6 6 6

This uses the "push x y times" construct y {({})} x, just that in this case both are the input number n.
({})  Pop and push n; evaluates to n
{({})}  A lambda that returns its argument unchanged,
        pushing its argument once onto the stack
{}    Pop n

Recursiva, 4 bytes
*aAa

Try it online!
Explanation:
*a  : Multiply a times(Here, 8) [8,8,8,8,8,8,8,8]
  A : List-ify a [8]
   a: All a's will be assigned with the first input argument) 8

Charcoal, 9 5 4 3 bytes
Ｅθθ

Try it online!
-4 bytes thanks to Neil, -1 byte thanks to Erik the Outgolfer
Explanation
Ｅ  Ｉθ Map with lambda returning first input cast to integer
  Ｎ    Implicit range over next (first) input

Ah, × vectorises these days, so to get list repetition, you need to embed it in a list?

Yeah, not sure if it's the best idea :/ but someone said so

Never mind, ＮθＥθθ is shorter even with non-vectorising ×.

Damnit lol I had this in mind, do you want to post a separate answer?

Ah, Mold still works, that's good to know!

Old McDonald had an integer list, ＥＩθＩθ... well, almost! Would ＥＩθθ be a valid answer?

Unfortunately no :P the OP states that "The elements need to be integers, not strings."

Save a byte by using Ｎ.

Oh yeah oops lol will do when I get back on a computer

Surely this isn't 35 bytes. I don't know Charcoal, but I'd guess it's in a format such that it's 4, right?

@cole Oops lol copied directly from TIO, thanks for pointing it out

Ohm, 4 bytes
DÄWî

Try it online!
DÄWî

D     duplicate
 Ä    push n onto the stack n times
  W   wrap the stack in a list
   î  cast to integer

Pyke, 3 bytes
]1*

Try it here!
]1  - Wrap the input into a list.
  * - Repeat the list.

J, 2 bytes
#~

Try it online!
# copy
~ self

Pari/GP, 16 bytes
n->[n|x<-[1..n]]

Try it online!
Or:
n->vector(n,x,n)

Try it online!
Or:
n->powers(1,n,n)

Try it online!

Stacked, 6 bytes
[:rep]

Try it online!
This is an anonymous function that takes input on the stack and leaves output on the stack. This simply takes the input, duplicates it, then repeats the input by the input.

QBasic 4.5, 48 bytes
INPUT a
DIM t(a)
FOR x=1TO a
t(x)=a
NEXT

Aceto, 3 bytes
Assumes the integer is on the stack already.
d×

This just duplicates the top stack element and then performs stack multiplication (i.e. Python's [x]*y).

SOGL V0.12, 2 bytes
∙r

Try it Here!
Outputs to the stack.
Explanation:
∙   multiply POP (string, defaults to input) by POP (number, defaults to the same input)
     vertically - so to an array of strings
 r  swap types - convert the strings to numbers

Brain-Flak, 28, 22 bytes
{(({}[()])<>[]())<>}<>

Try it online!
Normally, the version that uses one stack would be shorter. However, in this case it's 6 bytes longer:
(({})){({}<(({}))>[()])}{}{}

One stack in 24 bytes.

Gaia, 2 bytes
w×

Try it online!
w   Wrap input into list
 ×  Repeat (input) times

MY, 6 bytes
ωi×ω+↵

Try it online!
How?

ω, push the first command line argument evaluated
i, pop n; push [1...n]
×, pop a; pop b; push b*a. 0 is popped when there is nothing on the stack. Since commands vectorize ("vecify" in MY), it ends up being an array of n 0's.
ω, push the first command line argument evaluated
+, pop a; pop b; push b+a. Adds the command line argument to every item in the array of 0 repeated n times, giving us n repeated n times
↵, pop n; print n with a newline.

Prolog (SWI), 33 bytes
X*L:-maplist(=(X),L),length(L,X).

Try it online!

Tcl, 22 bytes
time {lappend L $n} $n

Try it online!

With built-ins:
Tcl, 13 bytes
lrepeat $n $n

Try it online!

MacOS bash, 12
jot $1 $1 $1

This also works on Linux if the jot package is installed, e.g. sudo apt install athena-jot.
Try it online.

Actually, 2 bytes
;α

Explanation:
;α
;   duplicate the input
 α  push a list containing n copies of n

α is not a builtin for this challenge by the usual definition, because it does not solve this challenge by itself. α takes the top stack element (call it a) and repeats the next stack element (b) a times. It's roughly equivalent to iterable multiplication in Python ([5, 1]*2 == [5, 5, 1, 1]), but also works on non-iterables (52α yields [5, 5]).
Try it online!

4, 32 bytes
3.700001000260201801500101010294

Try it online!
If you have concerns regarding the input format, please read this first.
Transpiles roughly as
grid[1] = grid[0] = input()
while grid[1] != 0:
  print(grid[0])
  grid[1] -= 1

this can only handle single-digit numbers properly

@TimothyGroote no; read the meta post. this handles numbers as bytes, because that's the main form of input for that language. input 1 is 48, and will print 1 (byte representation) 48 times.

Braingolf, 6 bytes
!A.$_=

Try it online!
Explanation
!A.$_=  Implicit input from commandline args
!A      Read top of stack without popping, run next operator that many times
  .     Duplicate top of stack
   $_   Pop top of stack
     =  Print stack

We have to pop the top of the stack because otherwise we'll have 1 too many copies of n. If we remove the ! and let A pop the top of the stack, duplicate will have nothing to duplicate.

Clojure, 13 bytes
#(repeat % %)

Coq, 68 bytes
fun n=>(fix f k n:=match n with|0=>nil|S n=>(k::f k n)%list end) n n

Of course there's a library function, giving 46 bytes:
Require List. Definition f n:=List.repeat n n.

Just found this lang and wanted to give it a go.
LOLCODE, 164 bytes
HAI 1.2
I HAS A CHZBRGR
GIMMEH CHZBRGR
CHZBRGR IS NOW A NUMBR
IM IN YR CRIB UPPIN YR HMBRGR TIL BOTH SAEM CHZBRGR AN HMBRGR
VISIBLE CHZBRGR
IM OUTTA YR CRIB
KTHXBYE

Try it online!

Pyt, 3 bytes
Đ⑴*

Explanation:
                Implicit input
Đ               Duplicates input
 ⑴             Pushes an array, [1,1,...,1], with input 1's, onto the stack
   *            Multiply the array element-wise by the input
                Implicit output

Try it online!

FORTH 21 Bytes
: B 0 DO DUP . LOOP ;

OUTPUT:
10 B
10 B 10 10 10 10 10 10 10 10 10 10

Gol><>, 5 bytes
:MR:B

Try it online!
Example full program & How it works
1AGIE;GDlR~
:MR:B

1AG          Register row 1 as function G
   IE;       Take number input; halt on EOF
      G      Call G
       D     Print the stack contents
        lR~  Empty the stack
             Repeat indefinitely

:M           Duplicate top and decrement
  R:         Duplicate n-1 times
    B        Return

Keg, 5 bytes
:(|:.

Try it online!

Arn, 7 bytes
|ÅF└¾c)

Explanation
Unpacked: v{_}\1=>
    \ Fold/map (in this case just map) with...
v{ A block with the key of v
  _ Input
}
      1=> Range, [1, in]

MAWP, 13 bytes
%@!1A[1A~!~]%

-15 bytes after integer input rework (Dion).
Try it!

This input change really effects a lot of answers... 13 bytes https://8dion8.github.io/MAWP/?code=%25%40!1A%5B1A~!~%5D%25&input=7

Integral, 6 Bytes
Outputs the list as individual stack elements joined by the newline.
If built-ins weren't banned, it would be possible via ♫ (1 bytes).

◙v◙♦▼e

Try it!
Explanation
◙      Duplicate input, in order to get around the edge case 1
 v◙    "◙": Create a copy of the operand, when evaluated
   ♦   Swap up a copy of the input
    ▼  Decrement
     e Repeat input-1 times: Duplicate stack

[Swift 3], 55 49 bytes
func a(n:Int)->[Int] {return (0..<n).map{_ in n}}

$0+n-$0 can be replaced by _ in n for -1 bytes. Additionally, you can print rather than return and ->[Int] to save tons of bytes. You can also remove Array and the space before it. This ends up being 41 bytes: func a(n:Int){print((0..<n).map{_ in n})}

Didn't realise you didn't need the Array there and interesting how the _ in n works, would never have thought of that. However, the challenge says to "return a list", which to me would suggest you need to return something, not just print it, but that may just be my interpretation. I've updated with the other suggestions though, thanks!

C++, 86 56 45 bytes
Thanks to @ceilingcat for saving 30 41 bytes!
#import<list>
#define f(n)std::list<int>(n,n)

Try it online!

REXX, 24 bytes
arg n
say copies(n' ',n)

Uses the built-in function copies(), and naturally, this being REXX, the copies are integers just as much as they are strings.

WendyScript, 10 bytes
#:(x)[x]*x

(#:(x)[x]*x)(5) // => [5,5,5,5,5]

Try it online!

V, 5 bytes
Du@"Ä

Try it online!

Pyth, 5 bytes
Super simple
.[QQY

Explanation:
.[QQY     Pad Y with eval(input) copies of eval(input)

Try it online!

8th, 42 37 bytes
Code
>r a:new ( r@ a:push ) r@ times rdrop

SED (Stack Effect Diagram) is: n -- a
Usage
: f >r a:new ( r@ a:push ) r@ times rdrop ;

ok> 5 f .
[5,5,5,5,5]

We could save another 6 bytes if we accept the idea of leaving numbers on r-stack after processing.

R, 7 bytes
0*1:n+n

Try it online!

This isn't a function nor a full program. You have to handle input and output: function(n)0*1:n+n, or cat(0*1:(n=scan())+n)

VBA, 75 Bytes
Defined Function that takes input n of expected type Integer and returns an array of length n filled with n to STDOUT
Function l(n)
Dim o
ReDim o(1To n)
For i=1To n
o(i)=n
Next
l=o
End Function

Excel VBA, 49 Bytes
Anonymous VBE immediate window function that takes input from range [A1] and outputs a array of range values, o, with bounds (1 To [A1], 1) to the VBE immediate window.
[A1].Resize([A1],1)=[A1]:o=Sheet1.UsedRange.Value

Imo, if your language has no lists, use the next closest thing.

Julia 12
~x=fill(x,x)

Also it kinda generalizes to tuples making tensors.
julia> ~3
3-element Array{Int64,1}:
 3
 3
 3

julia> ~tuple(2,4)
2×4 Array{Tuple{Int64,Int64},2}:
 (2, 4)  (2, 4)  (2, 4)  (2, 4)
 (2, 4)  (2, 4)  (2, 4)  (2, 4)

julia> ~tuple(2,4,3)
2×4×3 Array{Tuple{Int64,Int64,Int64},3}:
[:, :, 1] =
 (2, 4, 3)  (2, 4, 3)  (2, 4, 3)  (2, 4, 3)
 (2, 4, 3)  (2, 4, 3)  (2, 4, 3)  (2, 4, 3)

[:, :, 2] =
 (2, 4, 3)  (2, 4, 3)  (2, 4, 3)  (2, 4, 3)
 (2, 4, 3)  (2, 4, 3)  (2, 4, 3)  (2, 4, 3)

[:, :, 3] =
 (2, 4, 3)  (2, 4, 3)  (2, 4, 3)  (2, 4, 3)
 (2, 4, 3)  (2, 4, 3)  (2, 4, 3)  (2, 4, 3)

TI-BASIC, 12 bytes
Ans→dim(L₁:Ans(L₁+1

Assumes an empty list.

No, Ans, →, & dim(, 1 byte, L₁, 2 bytes, :, Ans, & (, 1 byte, L₁, 2 bytes, + & 1, 1 byte.

Whoops, thought Ans( was all one byte, derp.

Objective-C 107 Bytes
#define a NSMutableArray
-(a*)f:(int)n{a*m=[a arrayWithCapacity:n];for(int i=0;i<n;i++)m[i]=@(n);return m;}

A little macro abuse and a basic loop, everyone else took the good languages...
Usage
[self f:5];

returns an array of number objects of the given value

Microscript II, 14 bytes
$s{o`s`+s}sNv*

Ruby, 12 bytes
->(n){[n]*n}

13 bytes
Array.new n,n

dc, 21
?dsn[lnpr1-d0!=F]dsFx

Try it online!
Ungolfed:
# Read a number from standard input (?), save it to register n (sn) and leave a copy on the stack (d)
?dsn

# Function F: print register n as many times as the top of the stack shows
[            # start of macro
  lnp        # print register n
  r          # swap the counter to the top
  1-         # decrement counter
  d          # duplicate counter for the comparison
  0 !=F      # if counter is not zero run F again
]dsFx        # end of macro, save it to F (sF) and execute (d x)

Run on the command line like this:
echo 5 | dc dcscript

Output:
5
5
5
5
5

This shorter script works for n>1 (15 bytes):
? [d d z 1- <F]dsFx f

This uses the depth of the stack to determine when to stop.

This only prints n n times, it doesn't create a list or array containing n copies of n which is what the challenge asks for, unfortunately this not a valid solution.

@BMO: converting to a list is trivial: echo -n '['; echo 5 | dc dcscript | paste -sd, | tr -d \\n ; echo ']'

That would make it a bash submission though.

QBIC, 17 bytes
dim g(:)[a|g(b)=a

This is a direct port of my QBasic answer (48 bytes), and QBIC does what it does best: compressing QBasic.
Explanation
dim g(:) Defines an array of x elements, where x is a cmd line param
[a|      FOR b = 1 TO a (the : above creates 'a' and assigns the cmd line param to it)
g(b)=a   Set each array element to 'a'

Ly, 13 10 bytes
ns[>l<1-]>

Try it online!
Prints space-separated numbers. If outputting without a separator is allowed, ns[lu1-]; works for 9 bytes.
Explanation:
ns[>l<1-]>

ns         # take input and save it
  [        # loop
   >l<     # load save and push it to another stack
      1-   # decrement
        ]  # end loop
         > # go to other stack
           # implicitly print

F#, 32 bytes
let m n=List.map(fun x->n)[1..n]

Creates a list 1 to n, then mapping a function to each element to replace it with n.

Axiom, 23 bytes
f(x)==[x for i in 1..x]

This 15 bytes would be better
f(x)⊳[x|i∈1..x]

f(x) return the list contains x element x
but Axiom is a good approximation to that.
Goes under 15 bytes it seems too much golfed

Excel VBA, 26 Bytes
Anonymous VBE immediate window function that takes input, n from range [A1] and returns an array object X with n stuffed into it n times.
x=Split([Rept(A1&" ",A1)])

SNOBOL4 (CSNOBOL4), 41 bytes
R	R =ARRAY(N,N)	:(RETURN)
	DEFINE('R(N)')

Try it online!
ARRAY initializes an array with the given indices, in this case, 1:N. It has an optional argument which it uses to initialize all the values in the array.

///, 23 bytes
/i///0./.1//1/i,//.//i.

Try it online!
Since there is no other way to take input in ///, it is hard coded. Also, since /// is a string-based language, input is in unary.
Example with input 5:
/i/00000//0./.1//1/i,//.//i.

How it works (with example input 5):
/i/00000//0./.1//1/i,//.//i.    Program with input.
/i/00000/                       Replace i with input. This is to make 1 uniform input.
         /0./.1/                Replace "0." with ".1". This turns all the 0s to 1s in the later i without bothering the next piece of code.
                /1/i,/          Replace 1s with input and a comma. This places the input into where the 1s were, essentially replacing each unary char of the input with the input, delimited with commas.
                      /.//      Remove the period.
                          i.    Input with period, main thing being modified by code.

Python 3, 63 54 Bytes
Saved 9 bytes thanks to Xcoder
a=[];i=input()
for _ in" "*int(i):a+=(i);
print(a)

Same code but will print every iteration of the list, saves 2 bytes
a=[];i=input()
for _ in" "*int(i):a+=(i);print(a)

Thanks, although I am still trying to figure out how I could get rid of the variables I needed to set

You should post that as your answer, not going to copy it.

That's up to you :) However I already have my own answer.

Fortran (GFortran), 45 bytes
SUBROUTINE B(I)
INTEGER A(I)
A=I
PRINT*,A
END

Try it online!
This is a simple version, in which the subroutine is used to avoid the allocation stuff, since we have a unknown length array. The TIO link leads to a version with the full program, with 67 bytes in total.

K (oK), 4 bytes
Solution:
x#x:

Try it online!
Explanation:
5#5 means take from 5, 5 times. But doesn't appear we can do the same trick as APL/J to reduce this one down.
x#x: / the solution
  x: / save input as x
x#   / take from it x times

Stax, 3 bytes
]x*

Run and debug it
Internally it actually converts an integer to the array required but the implicit output changes it to codepoints. By default, output by codepoint is allowed though.
Explanation
]      Convert input to singleton
 x*    Repeat input times

y* does it without using the codepoint exemption. y is the first line of standard input by default.

True, but "The elements need to be integers, not strings".

12-basic, 17 14 bytes
?[X=INPUT()]*X

Try

Kotlin, 20 19 15 bytes
Shorter Kotlin answer using the List constructor.
{n->List(n){n}}

Try it online!
Ungolfed:
// lambda function
{ n ->
    List(n) { n }  // create a List of n Ints where each item is n
}

Because List is actually an interface, List() is actually a function that creates a List of the specified type (here figured out through inference) and a fixed size, using the given lambda to initialize the value of each item. { n } means the lambda will always return the value of n.

15

Japt -m, 1 byte
N

Try it online!
-m is a flag that runs the program on each item in the input. Because the input is a number, it gets turned into a range first. N is the input.

Gol><>, 7 bytes
I:R:~D;

This uses the convenient 'D' - Debug operator, which outputs the stack!
I       //Get integer input
 :R:    //Repeat input, double the number
    ~D; //Delete the last item in the stack(to get the right number) and output the entire stack with debug

Try it online!

lol, there's already a 5 byte one

@ASCII-only I didn't see that... Well, at the very least mine doesn't use a header, it does it on its own

Yeah well that's just the difference between a function and a program :P

Rockstar, 83 bytes
Rockstar only has string I/O so output is a comma delimited string, which may not be allowed by the spec. To conform with the spec, though, the second line ensures the elements in the actual array are integers.
listen to N
cast N
X's0
while N-X
let L at X be N
let X be+1

join L with ","
say L

Try it here (Code will need to be pasted in)

Bound, 6 bytes
ic1-Rc

Explaination:
i # Get input (for example 5) [5]
c # Copy the top element [5, 5]
1 # Put 1 onto the stack [5, 5, 1]
- # Subtraction [5, 4]
R # Pop the top element, repeat the next command that many times [5]
c # Copy the top element [5, 5, 5, 5, 5]

Try it online!

GolfScript, 5 bytes
~.])*

Try it online!
~       # Parse the input to an integer     5
 .      # Copy it                           5 5
  ]     # Put everything in an array       [5 5]
   )    # Remove the last element          [5] 5
    *   # Multiply                         [5 5 5 5 5]

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
First they came
"First they came..." is a poem by Martin Niemöller:
First they came for the Socialists, and I did not speak out-
Because I was not a Socialist.

Then they came for the Trade Unionists, and I did not speak out-
Because I was not a Trade Unionist.

Then they came for the Jews, and I did not speak out-
Because I was not a Jew.

Then they came for me-and there was no one left to speak for me.

Your task is to output the above. This is code-golf, so shortest code in bytes wins!
Rules

You may include extra whitespace that does not affect appearance. A single trailing newline is allowed.
Otherwise, the output must match exactly, including the location of newlines.
As per meta standards, you may output a list of strings. However, you must include the empty lines.

Note that I personally believe this is not a dupe because of how the poem is laid out - it needs some creativity to golf. Meta discussion about whether this is a dupe or not can be found here.

I'm not sure what this adds to the site above and beyond the RickRoll challenge.

Meta discussion

For once, I don't think this is a Rickroll dupe. There is meaningful structure here. The parallelism allows from different strategies. Reopening.

The structure is an argument in favour of being a dupe of the rickroll, not against.

The poem in question has much more structure than Never Gonna Give You Up, I don't see how it makes it more of a dupe target.

I'm dupe-hammering this again, because the meta consensus seems to be that it is in fact a dupe (by virtue of the fact that the meta question was closed as a dupe of other meta questions with the same consensus).

@Mego I can't find the meta consensus you are talking about that has that consensus. The only thing I could find said in this case it makes more sense to upvote, precisely because the OP has found a song that isn't just a duplicate of the rickroll and this question has quite a few upvotes.

@Stephen Look at the meta discussion linked in the comments. It's been closed as a dupe of other discussions where the consensus was "yes this is a dupe".

@Mego I don't see that in either other meta discussion. The first (about "Work it harder, make it better") has a clear consensus that not all song lyric questions are rickroll dupes, and the second ("I met a bear") has no consensus--two opposing answers with two points each.

SOGL V0.12, 103 102 101 bytes
 →∑‘¾ο╤Ε9‘}ψ⁴‘¹"4¡‘Q°‘:¹¹I{ū_:¹"Eā/}l6⁸SÆ□⁴↔b⅜╬I℮;YΥηκ*█⅞F^Κ⅜⁸{x⅔⁵⅟╚?Z‘O}"Ι╚╬√⅔δηvΧχ⁷⁾Η<υL┼!Ο'μΠ⁵╝⁷‘⁾

Try it Here!
Explanation (here I replaced the compressed strings with .. to save space):
..‘.‘..‘                              push "socialist", "trade unionist" and "jew"
        ¹                             wrap in an array: ["socialist", "trade unionist", "jew"]
         "..‘..‘                      push "first" and "then"
                :                     duplicate the then
                 ¹                    wrap in an array: ["first","then","then"]
                  ¹                   wrap those two in an array: [["socialist", "trade unionist", "jew"], ["first","then","then"]]
                   I                  rotate clockwise: [[first,socialist], [then,trade unionist], [then,jew]]
                    {         }       for each do, pushing the array
                     ū                  uppercase the 1st letter of each word in the array - ["First", "Socialist"]
                      _                 splat the contents on the stack   "First", "Socialist"
                       :                duplicate the 2nd one             "First", "Socialist", "Socialist"
                        ¹               wrap in an array                  ["First", "Socialist", "Socialist"]
                         "..‘           push "ŗ they came for the ŗs, and I did not speak out-\nBecause I was not a ŗ." with ŗ replaced with its appropriate item in the array
                             O          output that
                               "..‘   push "then they came for me-and there was no one left to speak for me."
                                   ⁾  uppercase the 1st letter of it
                                      implicitly output it in a new line

Could you add an explanation please?

@Nzall Forgot to, writing up

@Nzall Added an explanation

6502 machine code (C64), 229 bytes
Kind of boring, still doable on a C64 with a somewhat decent amount of bytes :)
00 C0 A9 17 8D 18 D0 A2 2C 86 FE A6 FE A0 C0 BD B6 C0 20 1E AB C6 FE 10 F2 60
C6 49 52 53 54 20 00 D4 48 45 4E 20 00 54 48 45 20 00 54 48 45 59 20 43 41 4D
45 20 00 46 4F 52 20 00 53 50 45 41 4B 20 00 41 4E 44 20 C9 20 44 49 44 20 4E
4F 54 20 00 4F 55 54 2D 0D 00 C2 45 43 41 55 53 45 20 C9 20 57 41 53 20 4E 4F
54 20 41 20 00 4D 45 2D 41 4E 44 20 54 48 45 52 45 20 57 41 53 20 4E 4F 20 4F
4E 45 20 4C 45 46 54 20 54 4F 20 00 4D 45 2E 00 2E 0D 00 53 2C 20 00 D3 4F 43
49 41 4C 49 53 54 00 D4 52 41 44 45 20 D5 4E 49 4F 4E 49 53 54 00 CA 45 57 00
0D 00 8C 35 3A 6B 2A 1F B4 90 B0 56 50 3A 41 93 B0 25 35 2A 1F B4 90 A1 56 50
3A 41 93 A1 25 35 2A 1F B4 90 97 56 50 3A 41 93 97 25 35 2A 18

Online demo
Usage: SYS49152
Explanation:
As this contains mostly data, instead of a meaningless disassembly listing, here's the ca65-style assembly source that creates this machine code:
.segment "LDADDR"
                .word   $c000           ; load address
.code
                lda     #$17            ; upper/lower mode
                sta     $d018           ; store in VIC register
                ldx     #revpoemsize    ; initialize ...
                stx     $fe             ; ... counter
loop:           ldx     $fe             ; load current position
                ldy     #$c0            ; highbyte of strings always same
                lda     revpoem,x       ; load lowbyte from table
                jsr     $ab1e           ; output 0-terminated string
                dec     $fe             ; decrement position
                bpl     loop            ; >=0 ? -> repeat
                rts                     ; done

first:          .byte   "First ", 0
then:           .byte   "Then ", 0
the:            .byte   "the ", 0
came:           .byte   "they came ", 0
for:            .byte   "for ", 0
speak:          .byte   "speak ", 0
didnot:         .byte   "and I did not ", 0
out:            .byte   "out-", $d, 0
wasnot:         .byte   "Because I was not a ", 0
noone:          .byte   "me-and there was no one left to ", 0
me:             .byte   "me.", 0
period:         .byte   ".", $d, 0
comma:          .byte   "s, ", 0
socialist:      .byte   "Socialist", 0
unionist:       .byte   "Trade Unionist", 0
jew:            .byte   "Jew", 0
p:              .byte   $d, 0

revpoem:        .byte   <me, <for, <speak, <noone, <came, <then, <p
                .byte   <period, <jew, <wasnot, <out, <speak, <didnot
                .byte   <comma, <jew, <the, <for, <came, <then, <p, <period
                .byte   <unionist, <wasnot, <out, <speak, <didnot, <comma
                .byte   <unionist, <the, <for, <came, <then, <p, <period
                .byte   <socialist, <wasnot, <out, <speak, <didnot, <comma
                .byte   <socialist, <the, <for, <came, <first
revpoemsize     = * - revpoem - 1

Python 3, 209 bytes
t='they came for '
s='First '
for i in'Socialist','Trade Unionist','Jew':s+=t+f'the {i}s, and I did not speak out-\nBecause I was not a {i}.\n\nThen '
print(s+t+'me-and there was no one left to speak for me.')

Try it online!
-5 thanks to Felipe Nardi Batista.

@Heiteira Sorry, but I can't leave the "Trade " part out of the output.

Perl 5, 185 bytes
print join" they came for ",First,(map"the ${_}s, and I did not speak out-
Because I was not a $_.

Then",Socialist,"Trade Unionist",Jew),"me-and there was no one left to speak for me."

Try it online!
Thanks to @Massa for -3 bytes!

Use Join and you can trim another five chairs or so

@Massa not sure I'm seeing how! Any more clues?

I'm on my mobile right now, but take a look at my perl6 answer below!

@Massa Ahhh, nice! Thanks! -3 in the end :)

Perl 6, 193 bytes
say join ' they came for ','First',«Socialist "Trade Unionist" Jew».map({"the {$_}s, but I did not speak out-
because I was not a $_.

Then"}),'me- and there was no one left to speak for me.'

Try it online!

C, 248 bytes
Thanks to @Zacharý for saving 9 bytes.
p(x,y){printf("%s they came for the %ss, and I did not speak out-\nBecause I was not a %s.\n\n",x,y,y);}f(){p("First","Socialist");p("Then","Trade Unionist");p("Then","Jew");puts("Then they came for me-and there was no one left to speak for me.");}

Try it online!

Can you move s directly into the printf statement?

@Zacharý Yes, of course.

247 bytes

C# (.NET Core), 248 246 242 bytes
a=>{string b=@", and I did not speak out-
Because I was not a ",c=" they came for ",d="Socialist",e="Trade Unionist";return$@"First{c+d}s{b+d}.

Then{c+e}s{b+e}.

Then{c}the Jews{b}Jew.

Then{c}me-and there was no one left to speak for me.";}

Actual newlines saved me a few bytes.
Try it online!
Saved 2 bytes thanks to Business Cat

Python 3, 203 bytes
print('First',*[f'the {s}s, and I did not speak out-\nBecause I was not a {s}.\n\nThen'for s in['Socialist','Trade Unionist','Jew']],'me-and there was no one left to speak for me.',sep=' they came for ')

Try it online!

sep= is a genius move! :-)

Befunge-93, 348 bytes
".em rof kaeps ot tfel eno on saw ereht dna-em rof emac yeht nehT"52*:v
v"d not speak out-"*25"Because I was not a "<   p5-2*89p1-2*89"vvJew."<
> "id I dna ">",sweJ>v"67+2p66+5p     v     ^p2-2*89"vTrade Unionist."<
>"tsriF">:#,v>",stsinoinU edarTv"67+3pv     ^   p3+66p40"^_Socialist."<
>"nehT"52*: v>",stsilaicoS@"67+3p     >" eht rof emac yeht "

Try it online!

Befunge, 293 274 270 bytes
62574732594932584832001v_@#:\0\!<
0-*84g+3/"P"\%"P"::+p00<_|#:-1g0
84!-"*":g+3/"P"\%"P"::+1\<+1_$#:^#-2\,-**
&First0 they came for %the Qs, and I did not speak out-*Because I was not a (.**
ThenOme-and there was no one left to speak for me.*$Jew*Socialist/Trade Unionist

Try it online!
This is a different approach to the existing Befunge solution. It uses a kind of linked list to store a dictionary of the common phrases, and then just has a simple list of values on the stack representing the order in which the phrases should be output.

Gaia, 179 175 bytes
⇓“the ”3ṁ“s, and I did not speak out-¶Because I was not a ”2ṃ“.¶¶Then
“ they came for
First”“Socialist“Trade Unionist“Jew”↓¦⇑“me-and there was no one left to speak for me.”]$

Try it online!
Explanation
3 functions are defined here (1 per line). The bottom one is called first. ¶ gets replaced by newlines.
⇓“the ”3ṁ“...”2ṃ“.¶¶Then  First helper function. Argument: s
⇓                         Push "Then they came for "
 “the ”                   Push "the "
       3ṁ                 Bring s to the top
         “...”            Push "s, and I did not speak out-¶Because I was not a "
              2ṃ          Push a copy of s
                “.¶¶Then  Push ".¶¶Then"

“ they came for   Helper function. No arguments.
“ they came for   Push " they came for "

First”“..“..“..”↓¦⇑“...”]$  Main function.
First”                      Push "First"
      “..“..“..”            Push the list ["Socialist" "Trade Unionist" "Jew"]
                ↓¦          Call the first helper function on each.
                  ⇑         Push "Then they came for "
                   “...”    Push "me-and there was no one left to speak for me."
                        ]$  Wrap the stack in a list and join with no separator.

JavaScript (ES6), 231 227 223 221 bytes
_=>`First${t=" they came for "}the Socialist${a=`s, and I did not speak out-
Because I was not a `}Socialist${t=`.

Then`+t}the ${(u="Trade Unionist")+a+u+t}the Jew${a}Jew${t}me-and there was no one left to speak for me.`

Try it

o.innerText=(
_=>`First${t=" they came for "}the Socialist${a=`s, and I did not speak out-
Because I was not a `}Socialist${t=`.

Then`+t}the ${(u="Trade Unionist")+a+u+t}the Jew${a}Jew${t}me-and there was no one left to speak for me.`
)()

Bubblegum, 149 132 129 bytes
00000000: 9d4d b515 0241 14cc af8a c991 1e70 0991  .M...A.......p..
00000010: 02fe bbfd e7b7 cb1a 523d ee0e d9f8 7453  ........R=....tS
00000020: 631d 5cc2 2b84 5432 2265 760c 6315 a654  c.\.+.T2"ev.c..T
00000030: a4d6 d92a 480a 0c20 5201 a91c ec8c 2987  ...*H.. R.....).
00000040: f2ae 1634 3924 6f79 6b2e c8ee 4dba 14eb  ...49$oyk...M...
00000050: 4130 4958 3ed9 9e18 128c a94c 95fc e3e0  A0IX>......L....
00000060: b6fd fa65 c88b 1fa7 7795 e77b 25d7 488a  ...e....w..{%.H.
00000070: 9d68 f898 8792 8c82 2307 a78e bb87 647d  .h......#.....d}
00000080: 03                                       .

Try it online!
Boring Bubblegum answer. Already beaten by SOGL, so that's good.
Credit for -17 bytes goes to Dom Hastings
-3 bytes by ovs

132 bytes. Still can't beat SOGL!

@DomHastings I don't think you'll ever beat SOGL with Bubblegum...

@EriktheOutgolfer I'm very glad of that fact too! I'd like to invest some time to play with it, incredibly expressive!

129 bytes

Retina, 176 bytes

 Socialists, Trade Unionists, Jews,1me-and there was no one left to2for me.
( .+?)s,
1the$& and I did not2out-¶Because I was not a$1.¶¶Then
^
First
1
 they came for
2
 speak

Try it online! Explanation: The 1 and 2 are just repeated strings which are long enough to be worth deduplicating. The First is added later to make it easier to select the placeholder for the repetitive portion, "they came for the [group]s, and I did not speak out-Because I was not a [group]. Then", which is expanded by the second stage.

174 bytes by also substituting  was no.

@DLosc Thanks! I won't edit the post though for historical reasons.

JavaScript (ES6), 210 207 206 203 bytes
A different approach to my other solution so figured it was worth editing it out to its own answer now that the challenge has been reopened.
_=>`First${["Socialist","Trade Unionist","Jew"].map(x=>t+`the ${x}s, and I did not speak out-
Because I was not a ${x}.

Then`,t=` they came for `).join``+t}me-and there was no one left to speak for me.`

Try it

o.innerText=(
_=>`First${["Socialist","Trade Unionist","Jew"].map(x=>t+`the ${x}s, and I did not speak out-
Because I was not a ${x}.

Then`,t=` they came for `).join``+t}me-and there was no one left to speak for me.`
)()

Java 8, 250 236 bytes
o->{String t=" they came for ",r="First";for(String s:"Socialist,Trade Unionist,Jew".split(","))r+=t+"the "+s+"s, and I did not speak out-\nBecause I was not a "+s+".\n\nThen";return r+t+"me-and there was no one left to speak for me.";}

Try it here.

PowerShell, 211 202 198 bytes
-13 bytes thanks to @Veskah
$a,$b='First',' they came for'
'Socialist','Trade Unionist','Jew'|%{"$a$b the $_`s, and I did not speak out-
Because I was not a $_.
";$a='Then'}
"$a$b me-and there was no one left to speak for me."
Try it online!
I'm sure this can be golfed down a little bit.

202 bytes with a bit of restructuring

Have 4 more bytes

SQL 269 bytes
declare @ char(18)='They came for the ',@a char(49)='s, and I did not speak out-
Because I was not a '
print'First '+@+'Socialist'+@a+'Socialist.

'+@+'Trade Unionist'+@a+'Trade Unionist.

'+@+'Jew'+@a+'Jew.

'+@+' me-and there was no one left to speak for me.'

Hi, welcome to PPCG! I've edited your post to add some formatting. As for the actual code, I think the leading words "Then " are missing in the last three sentences, and the last sentence now states "They came for the me-..." instead of "Then they came for me-...".

Proton, 219 bytes
t='they came for'for i:'Socialist','Trade Unionist','Jew'print(i[0]=='S'? 'First':'Then',t,'the',i+'s, and I did not speak out-
Because I was not a',i+'.
')print('Then',t,'me-and there was no one left to speak for me.')

Try it online!

Python 2, 246 bytes
First time I tried compressing the string an returning it. Aparently it takes more bytes than other approaches. Is there anything left to golf?
import zlib,base64
print zlib.decompress(base64.b64decode('eJyd0DEOwjAMBdA9p/gHoD0EAxJdgQNYiatGtDaKU1XcvikUdSkDjLb/f4NPMVlG7vgJTwOj1bRMuKiP1EfLdgBJwBkhBohm2IPpDh1z5Y7saTQux4nsdaStWDt37Vh27JtElT/oT++73PD0K1oq+97A1QKVZeI1DxVGz215mK7uO1nPf1Zu5g=='))

Try it online!

Japt, 153 150 149 147 bytes
`{=` ey ¯´ f `}´-d tre °s no e ¤ft  speak f ´.`i`Sáû\E
TÎè UÍát
Jew`·rÈ+U+`e {Y}s, d I ¹d not speak t-
Be¯«e I °s not a {Y}.

Tn`}`Fir¡

Test it
1 byte saved thanks to Oliver

Röda, 204 bytes
{t="Then"c=" they came for";["First","Socialist",t,"Trade Unionist",t,"Jew"]|[`$_$c the ${_}s, and I did not speak out-
Because I was not a $_2.

`];[`$t$c me-and there was no one left to speak for me.`]}

Try it online!

PHP, 194 bytes
First<?=$t=" they came for ";foreach([Socialist,"Trade Unionist",Jew]as$s)echo"the ${s}s, and I did not speak out-
Because I was not a $s.

Then$t"?>me-and there was no one left to speak for me.

Try it online.

C (gcc), 244 bytes
f(c){for(c=0;c<3;printf("%s they came for the %ss, and I did not speak out-\nBecause I was not a %2$s.\n\n",c++?"Then":"First",c^2?c?"Trade Unionist":"Socialist":"Jew"));puts("Then they came for me-and there was no one left to speak for me.");}

Try it online!

Python 3, 208 bytes
print(' they came for '.join(["First"]+[f"the {i}s, and I did not speak out-\nBecause I was not a {i}.\n\nThen"for i in['Socialist','Trade Unionist','Jew']]+['me-and there was no one left to speak for me.']))

Try it online!
-1 thanks to @Step Hen

Then "for -> Then"for and you're beating the other Python answers :)

@StepHen Thanks for noticing the extra space! :-)

Clojure, 285 bytes
(fn[](doseq[i(range 4):let[c["Socialist""Trade Unionist""Jew"""]f #(if(< i 3)% %2)]](println(if(= i 0)"First""Then")"they came for"(str(f(str"the "(c i)"s, ")"me-")(f"and I did not speak out-\n""and there was no one left to speak for me.")(f(str"Because I was not a "(c i)".\n")"")))))

This was a fun little challenge. I ended up almost entirely rewriting most of it a couple of times because I realized I was doing something overly roundabout. There are still a couple areas that could probably be touched up, but I'm pretty happy with how it turned out, even if I'm only "compressing" the original by 54 bytes.
repl.io
See the pre-golfed code for an explanation:
(defn ftc []
  ; Loop over the lines numbers for reference
  (doseq [i (range 4)
          :let [; Added a dummy last "class" since "me-" wasn't necessary,
                ;  and only having 3 elements was causing OOB errors.
                classes ["Socialist" "Trade Unionist" "Jew" ""]

                ; A helper function that executes either its first or second argument
                ;  depending on if the current line is one of the first 3 lines.
                if-first-three-lines #(if (< i 3) % %2)]]

    ; An implicit space is inserted between each of the args to println
    (println
      ; Decide on the opener
      (if (= i 0) "First" "Then")

      "they came for"

      ; Start string concatenation because the implicit space
      ;  begins complicating things.
      (str
        ; Decide which "class" the line belongs to
        (if-first-three-lines
          (str "the " (classes i) "s, ")
          "me-")

        ; Decide on the line ending
        (if-first-three-lines
          "and I did not speak out-\n"
          "and there was no one left to speak for me.")

        ; Then pick the trailer
        (if-first-three-lines
          (str "Because I was not a " (classes i) ".\n")
          "")))))

05AB1E, 124 119 bytes
.•RYÁ Wö∍®Ø’áÅÚ)’Òü•'x¡™vy„€Û‚½#NĀè™“ÿ€»‹é€‡€€ ÿs,€ƒ Iƒ§€–¡´€Ä-“©¶y“ƒ« I€¥€–€… ÿ.“.ª¶¶}®19£“€á-and€Ç€¥€¸€µ…¸€„¡´€‡€á.“J

Try it online.
Explanation:
.•RYÁ Wö∍®Ø’áÅÚ)’Òü•
                  # Push compressed string "socialistxtrade unionistxjew"
 'x¡             '# Split it on "x": ["socialist","trade unionist","jew"]
    ™             # Convert each word to Titlecase: ["Socialist","Trade Unionist","Jew"]
v                 # Loop `y` over each of these strings:
 y                #  Push string `y`
 „€Û‚½            #  Push dictionary string "first then"
      #           #  Split on spaces: ["first","then"]
       N          #  Push the index of the loop
        Ā         #  Truthify it (0 remains 0; every other number becomes 1)
         è        #  Use it to index into the list
          ™       #  Titlecase it
 “ÿ€»‹é€‡€€ ÿs,€ƒ Iƒ§€–¡´€Ä-“
                  #  Push dictionary string "ÿ they came for the ÿs, and I did not speak out-"
                  #  where the "ÿ" are automatically filled with the strings at the top of the stack
  ©               #  Save it in the register (without popping)
 ¶                #  Push a newline "\n"
 y                #  Push string `y` again
 “ƒ« I€¥€–€… ÿ.“  #  Push dictionary string "because I was not a ÿ."
                  #  where the "ÿ" is automatically filled again with the string
  .ª              #  Sentence case it: "because" becomes "Because"
 ¶¶               #  Push two newline characters "\n\n"
}                 # After the loop:
®                 # Push the string from the register:
                  #  "Then they came for the Jews, and I did not speak out-"
 19£              # Only leave the first 19 characters: "Then they came for "
“€á-and€Ç€¥€¸€µ…¸€„¡´€‡€á.“
                  # Push dictionary string "me-and there was no one left to speak for me."
J                 # Then join everything on the stack together (and output implicitly)

See this 05AB1E tip of mine (sections How to use the dictionary? and How to compress strings not part of the dictionary?) to understand why:

.•RYÁ Wö∍®Ø’áÅÚ)’Òü• is "socialistxtrade unionistxjew"
„€Û‚½ is "first then"
“ÿ€»‹é€‡€€ ÿs,€ƒ Iƒ§€–¡´€Ä-“ is "ÿ they came for the ÿs, and I did not speak out-"
“ƒ« I€¥€–€… ÿ.“ is "because I was not a ÿ."
“€á-and€Ç€¥€¸€µ…¸€„¡´€‡€á.“ is "me-and there was no one left to speak for me."

Text, 348 bytes
First they came for the Socialists, and I did not speak out-
Because I was not a Socialist.

Then they came for the Trade Unionists, and I did not speak out-
Because I was not a Trade Unionist.

Then they came for the Jews, and I did not speak out-
Because I was not a Jew.

Then they came for me-and there was no one left to speak for me.

This is the shortest possible version in its language, and is on par with the Befunge-93 answer at time of writing.

As with pretty much all "Text" answers, this is boring and lazy

@Jo King The notable bit is that it's the same length as the Befunge-93 answer.


text:
Keep/Drop/Increase Sequence
Here is the sequence I'm talking about:
{1, 4, 5, 9, 10, 11, 16, 17, 18, 19, 25, 26, 27...}

Starting from 1, keep 1, drop the next 2, keep the next 2, drop 3, keep 3 and so on. Yes, it's on OEIS (A064801), too!
The Challenge
Given an integer n>0, find the nth term of the above sequence
Test Cases
Input -> Output
1->1
22->49
333->683
4444->8908
12345->24747

This is code golf so the shortest answer in bytes wins! Good luck!

related

May we choose between 0 and 1 indexing?

@Mr.Xcoder I'm afraid not. This is only 1-indexed

May we return a list containing all the elements in order?

@WheatWizard this is totally unacceptable. sorry

Java (OpenJDK 8), 45 44 bytes
n->{int i=0;for(;++i<n;n-=i);return~-n+i*i;}

Try it online!
-1 byte thanks to @Nevay
After staring at this for a while, I noticed a pattern. Every time we drop n numbers, the next number in the sequence is a perfect square. Seeing this, I mentally broke the sequence into convenient chunks: [[1],[4,5],[9,10,11],...] Basically, the ith chunk starts with i*i, and iterates upwards for i elements.
To find the nth number in this sequence, we want to find first which chunk the number is in, and then which position in the chunk it occupies. We subtract our increment number i from n until n is less than i (which gives us our chunk), and then simply add n-1 to i*i to get the correct position in the chunk.
Example:
n = 8
n > 1? Yes, n = n - 1 = 7
n > 2? Yes, n = n - 2 = 5
n > 3? Yes, n = n - 3 = 2
n > 4? No, result is 4 * 4 + 2 - 1 = 17

You can use return~-n+i*i; to save 1 byte.

Python 3, 47 46 bytes
1 byte thanks to Mr. Xcoder.
def f(n):a=round((2*n)**.5);return~-n+a*-~a//2

Try it online!
VERY fast for higher numbers

46 bytes: def f(n):a=round((2*n)**.5);return~-n+a*-~a//2. Not sure though... Clever approach!

Aw, double lambdas is one extra byte, I was hoping that would save a byte...

Why did one downvote this? Is there any problem with the approach that we didn't notice?

@Mr.Xcoder maybe because of the corky remark.

a*(a+1) is even for every integer. Does Python complain about float division on integers? Does it complain about bitwise operations on floats? If not: (2*n)**.5+.5|0.

you can save a byte replacing n+a*-~a with n-a*~a: def f(n):a=round((2*n)**.5);return~-n-a*~a//2 you can save even more in python 3.8 with walrus

Haskell, 48 43 41 bytes
n#l=[l..l+n]++(n+1)#(l+2*n+3)
((0:0#1)!!)

4 extra bytes for 1-based indexing instead of 0-based. An unnecessary restriction, IMHO.
Try it online!
n#l             -- n is one less than the number of element to keep/drop and
                -- l the next number where the keep starts
   [l..l+n]     -- keep (n+1) numbers starting at l
   ++           -- and append a recursive call
   (n+1)#       -- where n is incremented by 1 and
      (l+2*n+3) -- l skips the elements to keep & drop

0#1             -- start with n=1 and l=0 and
 0:             -- prepend a dummy value to shift from 0 to 1-based index
    !!          -- pick the i-th element from the list

Haskell, 33 bytes
An anonymous function. Use as ((!!)$0:do n<-[1..];[n^2..n^2+n-1]) 1
(!!)$0:do n<-[1..];[n^2..n^2+n-1]

Try it online!

Constructs the sequence as an infinite list, then indexes into it with !!. The 0: is a dummy element to adjust from 0- to 1-based indexing.
The range [n^2..n^2+n-1] constructs a subsequence without gaps, starting with the square of n and containing n numbers.
The do notation concatenates the constructed ranges for all n>=1.

Jelly, 8 bytes
Ḷ+²µ€Ẏ⁸ị

Try it online!

Python 3, 46 bytes
f=lambda x,y=0,z=0:y<x and f(x,y+z,z+1)or~-y+x

Try it online!

Same algorithm...

TeX, 166 bytes
\newcommand{\f}[1]{\count0=0\count1=0\loop\advance\count0 by\the\count1\advance\count1 by1\ifnum\count0<#1\repeat\advance\count0 by#1\advance\count0 by-1
\the\count0}

Usage
\documentclass[12pt,a4paper]{article}
\begin{document}
\newcommand{\f}[1]{\count0=0\count1=0\loop\advance\count0 by\the\count1\advance\count1 by1\ifnum\count0<#1\repeat\advance\count0 by#1\advance\count0 by-1
\the\count0}

\f{1}

\f{22}

\f{333}

\f{4444}

\f{12345}
\end{document}

05AB1E, 12 bytes
LεÝÁćn+}˜¹<è

Try it online!

Very cool approach!

@Emigna Well, I'm just doing [0..a-1] + a**2, the cool thing here imo is just the ÝÁćn+ instead of D<Ýsn+.

εÝÁćn+} can be DL<sn+ for -1

Perl 6, 43 bytes
{(1..*).rotor({++$=>++$+1}...*).flat[$_-1]}

Test it
Expanded:
{  # bare block lambda with implicit parameter ｢$_｣

  ( 1 .. * )                  # range starting from 1

  .rotor(                     # break it into chunks

    { ++$  =>  ++$ + 1} ... * # infinite Seq of increasing pairs
    #   1  =>    1 + 1    ==>   1 => 2 ( grab 1 skip 2 )
    #   2  =>    2 + 1    ==>   2 => 3
    #   3  =>    3 + 1    ==>   3 => 4
    # ...  =>  ... + 1

  ).flat\                     # reduce the sequence of lists to a flat sequence
  [ $_ - 1 ]                  # index into the sequence
                              # (adjusting to 0-based index)
}

(1..*).rotor({++$=>++$+1}...*) produces:

(
 (1,),
 (4, 5),
 (9, 10, 11),
 (16, 17, 18, 19),
 (25, 26, 27, 28, 29),
 ...
).Seq

Mathematica, 37 bytes
Flatten[Range@#+#^2-1&~Array~#][[#]]&

Explanation
Range@#+#^2-1&

Function which takes a positive integer # and returns the run of # consecutive numbers in the sequence.
...~Array~#

Produces the list of all such runs up to the input #
Flatten[...][[#]]

Flattens the resulting list and returns the #th element.

Javascript, 43 38 bytes
n=>eval("for(r=1;n>r;)n-=r++;r*r+n-1")

Try it online!
I use the fact, that for each triangular number plus one, the result is a square number.
As an example: triangular numbers are 0, 1, 3, 6, 10... so for 1, 2, 4, 7, 11... we observe 1, 4, 9, 16, 25... in our sequence.
If the index is somewhere between these known numbers, the elements of our sequence only advance by one. For instance, to calculate the result for 10, we take 7 (as a triangular number plus one), take the result (16) and add 10-7=3. Thus, 16+3=19.

Vyxal, 8 bytes
v₍ʁ²ṠfJi

Try it Online!
Would beat Jelly if zero-indexing were allowed (remove J).
v₍ʁ²ṠfJi
v        # For each in a range [1, n]:
 ₍       #  Apply both of the next two elements and wrap in a list:
  ʁ      #   Range [0, n), and:
   ²     #   Square n
    Ṡ    # Sum each (vectorizing)
         # For an input of 4, this will give [[1], [4, 5], [9, 10, 11], [16, 17, 18, 19]]
         # Basically, for each x in [1, n], add x^2 to each in [0, x)
     f   # Flatten
      J  # Prepend the input to the beginning (doesn't matter what we prepend)
       i # Index the input into this

cQuents, 27 bytes
#R(2B)^.5)|1:b~-B+A*-b~A//2

Try it online!
Currently a port of Leaky's Python answer, I think there's a better way though.

Try my alternative algorithm

Swift 3, 72 bytes
Port of my Python solution.
func f(_ x:Int,_ y:Int=0,_ z:Int=0)->Int{return y<x ?f(x,y+z,z+1):y+x-1}

Test Suite.

C# (Mono), 164 bytes
using System.Linq;n=>{var a=new int[1]{1}.ToList();for(int i=1,m;a.Count<n;a.AddRange(new int[++i*2].Select((_,d)=>m+d+1).Skip(i).Take(i)))m=a.Max();return a[n-1];}

Try it online!

Perl 5, 33 + 1 (-p) = 34 bytes
$\+=$.--?1:2+($.=++$s)while$_--}{

Try it online!

MATL, 12 bytes
:"@U@:q+]vG)

Try it online!
Explanation
:        % Push range [1 2 ... n], where n is implicit input
"        % For each k in that range
  @U     %   Push k^2
  @:     %   Push range [1 2 ... k]
  q      %   Subtract 1: gives [0 1 ... k-1]
  +      %   Add: gives [k^2 k^2+1 ... k^2+k-1]
]        % End
v        % Concatenate all numbers into a column vector
G)       % Get n-th entry. Implicitly display

Tampio, 310 308 bytes
n:n uni on n unena 1:lle
a unena k:lle on a vuona k:lla vähennettynä a:sta ja k
a vuona nollalla ja k on a
a vuona k:lla vähennettynä nollasta ja k on a
a vuona b:n seuraajalla ja k on yhteenlaskun kutsuttuna k:n kerrottuna 2:lla arvolla ja k:n vähennettynä a:sta arvolla unena k:n seuraajalle seuraaja

Usage: 4:n uni evaluates to 9.
Explanation:
n:n uni on n unena 1:lle
uni(n)  =  n `uni` 1

a unena k:lle on  a vuona  k:lla vähennettynä a:sta ja k
a `uni` k     =  (a `vuo` (k     `vähennetty` a)    )  k

 a vuona nollalla ja k on a
(a `vuo` 0        )  k =  a

 a vuona  k:lla vähennettynä nollasta ja k on a
(a `vuo` (k     `vähennetty` 0)       )  k =  a

 a vuona  b:n seuraajalla ja k on
(a `vuo` (b   + 1)        )  k =

 yhteenlaskun kutsuttuna k:n kerrottuna 2:lla arvolla
(yhteenlasku            (k   *          2     )

 ja k:n vähennettynä a:sta arvolla unena  k:n seuraajalle seuraaja
((  k   `vähennetty` a     )       `uni` (k   + 1)   )  ) + 1

From standard library:
a `vähennetty` b = b - a
yhteenlasku a b  = a + b

JavaScript (ES6), 33 bytes
Recursive solution inspired by Xanderhall's observations.
f=(n,x=1)=>n<x?n+x*x-1:f(n-x,++x)

Try it

o.innerText=(
f=(n,x=1)=>n<x?n+x*x-1:f(n-x,++x)
)(i.value=12345);oninput=_=>o.innerText=f(+i.value)
<input id=i type=number><pre id=o>

Python 3, 50 bytes
def f(n):
 a=i=0
 while a<n:a+=i;i+=1
 return~-a+n

Try it online!

This would really benefit from a full-program port to Python 2 (46 bytes - would tie the recursive approach)

Mathematica, 82 bytes
Complement[Range[3#],Array[#+⌊((r=Sqrt[1+8#])-1)/2⌋⌊(r+1)/2⌋/2&,3#]][[#]]&

Python, 40 bytes
lambda n:(round((2*n)**.5)+.5)**2//2+n-1

Try it online!
Optimizing Leaky Nun's expression.

Python, 41 bytes
f=lambda n,k=1:n*(n<=k)or-~f(n-k,k+1)+2*k

Try it online!
Recursive expression.

Javascript (ES6) 100 98 Bytes
var k=n=>{var s=[],i=1,c=1,j;while(s.length<n){for(j=i;j<i+c;j++){s.push(j)}i+=c*2+1;c++}return s}

Kind of did this one fast, so I bet there is a lot of room for improvement, just basic loops and counters.

Retina, 27 bytes
.+
$*
((^1|1\2)+)1
$1$2$&
1

Try it online! Port of @LeakyNun's Python answer. The first and last stages are just boring decimal ⇔ unary conversion. The second stage works like this: ((^1|1\2)+) is a triangular number matcher; $1 is the matched triangular number while $2 is its index. The trailing 1 means it matches the largest triangular number strictly less than the input, thus resulting in exactly one fewer iteration than the Python loop, meaning that $1 is equivalent to a-i and $2 to i-1 and their sum is a-1 or ~-a as required. ($& just prevents the match from being deleted from the result.) Note that for an input of 1 no matching happens and the output is simply the same as the input. If you were perverse you could use ^((^1|1\2)*)1 to match in that case too.

C (gcc), 38 bytes
Using @Xanderhall's algorithm here
i;f(n){for(i=0;++i<n;n-=i);n=n-1+i*i;}

Try it online!

PHP, 48 42 37+1 bytes
ported from Leaky Nun´s answer
while($argn>$a+=$i++);echo$a+~-$argn;

Run as pipe with -F or try it online.
direct approach, 42+1 bytes
(ported from Leaky Nun´s other answer)
<?=($a=(2*$argn)**.5+.5|0)*-~$a/2+~-$argn;

Run as pipe with -nR or uncomment in above TiO.
older iterative solution, 48+1 bytes
for(;$argn--;$n++)$c++>$z&&$n+=++$z+$c=1;echo$n;

Ruby, 37 36 bytes
-1 byte thanks to Steffan
Port of Leaky Nun's Python 3 answer.
->n{~-n-(a=((2*n)**0.5).round)*~a/2}

Attempt This Online!

you can save a byte replacing +-~a/2 with -~a/2: ->n{~-n-(a=((2*n)**0.5).round)*~a/2}

@Steffan Nice, thanks.

TI-Basic, 41 22 bytes
Input N
int(.5+√(2N
N-1+.5Ans(Ans+1

Port of Leaky Nun's Python 3 answer.
I was quite happy with my previous 41-byte solution so here it is:
Input N
For I,1,N
For J,1,I(N>0
DS<(N,0
Ans+1
Ans+1
End
End
Ans-1

Needs a fresh calculator, or at least Ans initialized to 0

Japt, 9 bytes
0-indexed
g°Uô²cÈóY

Try it
g°Uô²cÈóY     :Implicit input of integer U
g             :Index into
 °U           :  Prefix increment U
   ô          :  Range [0,U]
    ²         :  Square each
     cÈ       :  Flat map each X at 0-based index Y
       óY     :    Range [X,X+Y)