text:
The Three 'R's: Reverse, Reorder, Repeat
While doodling around with numbers, I found an interesting permutation you can generate from a list of numbers. If you repeat this same permutation enough times, you will always end up back at the original array. Let's use the following list:
[1, 2, 3, 4, 5]

as an example

Reverse the array. Now our array is
[5, 4, 3, 2, 1]

Reorder (swap) each pair. Our list has 2 pairs: [5, 4], and [3, 2]. Unfortunately, we can't group the 1 into a pair, so we'll just leave it on it's own. After swapping each pair, the new array is:
[4, 5, 2, 3, 1]

Repeat steps 1 and 2 until we return to the original array. Here are the next 4 steps:
Step 2:
Start:          [4, 5, 2, 3, 1]
Reversed:       [1, 3, 2, 5, 4]
Pairs Swapped:  [3, 1, 5, 2, 4]

Step 3:
Start:          [3, 1, 5, 2, 4]
Reversed:       [4, 2, 5, 1, 3]
Pairs Swapped:  [2, 4, 1, 5, 3]

Step 4:
Start:          [2, 4, 1, 5, 3]
Reversed:       [3, 5, 1, 4, 2]
Pairs Swapped:  [5, 3, 4, 1, 2]

Step 5:
Start:          [5, 3, 4, 1, 2]
Reversed:       [2, 1, 4, 3, 5]
Pairs Swapped:  [1, 2, 3, 4, 5]

# No more steps needed because we are back to the original array

If the length of the list, n is odd, it will always take exactly n steps to return to the original array. If n is even, it will always take 2 steps to return to the original array, unless n is 2, in which case it will take 1 step (because reversing and swapping is the same thing).

Your task for today (should you choose to accept it) is to visualize this set of steps for lists of arbitrary lengths. You must write a program or function that takes a single positive integer n as input, and does this set of steps for the list [1, n]. You must output each intermediate step along the way, whether that means printing each step, or returning them all as a list of steps. I'm not very picky about the output format, as long as it's clear that you are generating every step. This means (for example) any of these:

Outputting every step as a list to STDOUT
Returning a list of lists
Returning a list of string representations of each step
Returning/outputting a matrix

would be acceptable.
You must also output the original array, whether that comes at the end or at the beginning is up to you. (technically, both are correct)
You will have to handle the edge case of 2 taking 1 step instead of 2, so please make sure your solution works with an input of 2 (and 1 is another potential edge case).
As usual, this is code-golf, so standard loopholes apply, and try to make your solution shorter than any other in the language of your choice (or even try to beat another language that is typically shorter than yours if you're feeling up for a challenge).
Test IO
1:
[1]

2:
[1, 2]

3:
[2, 3, 1]
[3, 1, 2]
[1, 2, 3]

4:
[3, 4, 1, 2]
[1, 2, 3, 4]

5:
[4, 5, 2, 3, 1]
[3, 1, 5, 2, 4]
[2, 4, 1, 5, 3]
[5, 3, 4, 1, 2]
[1, 2, 3, 4, 5]

7:
[6, 7, 4, 5, 2, 3, 1]
[3, 1, 5, 2, 7, 4, 6]
[4, 6, 2, 7, 1, 5, 3]
[5, 3, 7, 1, 6, 2, 4]
[2, 4, 1, 6, 3, 7, 5]
[7, 5, 6, 3, 4, 1, 2]
[1, 2, 3, 4, 5, 6, 7]

9:
[8, 9, 6, 7, 4, 5, 2, 3, 1]
[3, 1, 5, 2, 7, 4, 9, 6, 8]
[6, 8, 4, 9, 2, 7, 1, 5, 3]
[5, 3, 7, 1, 9, 2, 8, 4, 6]
[4, 6, 2, 8, 1, 9, 3, 7, 5]
[7, 5, 9, 3, 8, 1, 6, 2, 4]
[2, 4, 1, 6, 3, 8, 5, 9, 7]
[9, 7, 8, 5, 6, 3, 4, 1, 2]
[1, 2, 3, 4, 5, 6, 7, 8, 9]

And for good measure, here's one giant test case:
27:
[26, 27, 24, 25, 22, 23, 20, 21, 18, 19, 16, 17, 14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3, 1]
[3, 1, 5, 2, 7, 4, 9, 6, 11, 8, 13, 10, 15, 12, 17, 14, 19, 16, 21, 18, 23, 20, 25, 22, 27, 24, 26]
[24, 26, 22, 27, 20, 25, 18, 23, 16, 21, 14, 19, 12, 17, 10, 15, 8, 13, 6, 11, 4, 9, 2, 7, 1, 5, 3]
[5, 3, 7, 1, 9, 2, 11, 4, 13, 6, 15, 8, 17, 10, 19, 12, 21, 14, 23, 16, 25, 18, 27, 20, 26, 22, 24]
[22, 24, 20, 26, 18, 27, 16, 25, 14, 23, 12, 21, 10, 19, 8, 17, 6, 15, 4, 13, 2, 11, 1, 9, 3, 7, 5]
[7, 5, 9, 3, 11, 1, 13, 2, 15, 4, 17, 6, 19, 8, 21, 10, 23, 12, 25, 14, 27, 16, 26, 18, 24, 20, 22]
[20, 22, 18, 24, 16, 26, 14, 27, 12, 25, 10, 23, 8, 21, 6, 19, 4, 17, 2, 15, 1, 13, 3, 11, 5, 9, 7]
[9, 7, 11, 5, 13, 3, 15, 1, 17, 2, 19, 4, 21, 6, 23, 8, 25, 10, 27, 12, 26, 14, 24, 16, 22, 18, 20]
[18, 20, 16, 22, 14, 24, 12, 26, 10, 27, 8, 25, 6, 23, 4, 21, 2, 19, 1, 17, 3, 15, 5, 13, 7, 11, 9]
[11, 9, 13, 7, 15, 5, 17, 3, 19, 1, 21, 2, 23, 4, 25, 6, 27, 8, 26, 10, 24, 12, 22, 14, 20, 16, 18]
[16, 18, 14, 20, 12, 22, 10, 24, 8, 26, 6, 27, 4, 25, 2, 23, 1, 21, 3, 19, 5, 17, 7, 15, 9, 13, 11]
[13, 11, 15, 9, 17, 7, 19, 5, 21, 3, 23, 1, 25, 2, 27, 4, 26, 6, 24, 8, 22, 10, 20, 12, 18, 14, 16]
[14, 16, 12, 18, 10, 20, 8, 22, 6, 24, 4, 26, 2, 27, 1, 25, 3, 23, 5, 21, 7, 19, 9, 17, 11, 15, 13]
[15, 13, 17, 11, 19, 9, 21, 7, 23, 5, 25, 3, 27, 1, 26, 2, 24, 4, 22, 6, 20, 8, 18, 10, 16, 12, 14]
[12, 14, 10, 16, 8, 18, 6, 20, 4, 22, 2, 24, 1, 26, 3, 27, 5, 25, 7, 23, 9, 21, 11, 19, 13, 17, 15]
[17, 15, 19, 13, 21, 11, 23, 9, 25, 7, 27, 5, 26, 3, 24, 1, 22, 2, 20, 4, 18, 6, 16, 8, 14, 10, 12]
[10, 12, 8, 14, 6, 16, 4, 18, 2, 20, 1, 22, 3, 24, 5, 26, 7, 27, 9, 25, 11, 23, 13, 21, 15, 19, 17]
[19, 17, 21, 15, 23, 13, 25, 11, 27, 9, 26, 7, 24, 5, 22, 3, 20, 1, 18, 2, 16, 4, 14, 6, 12, 8, 10]
[8, 10, 6, 12, 4, 14, 2, 16, 1, 18, 3, 20, 5, 22, 7, 24, 9, 26, 11, 27, 13, 25, 15, 23, 17, 21, 19]
[21, 19, 23, 17, 25, 15, 27, 13, 26, 11, 24, 9, 22, 7, 20, 5, 18, 3, 16, 1, 14, 2, 12, 4, 10, 6, 8]
[6, 8, 4, 10, 2, 12, 1, 14, 3, 16, 5, 18, 7, 20, 9, 22, 11, 24, 13, 26, 15, 27, 17, 25, 19, 23, 21]
[23, 21, 25, 19, 27, 17, 26, 15, 24, 13, 22, 11, 20, 9, 18, 7, 16, 5, 14, 3, 12, 1, 10, 2, 8, 4, 6]
[4, 6, 2, 8, 1, 10, 3, 12, 5, 14, 7, 16, 9, 18, 11, 20, 13, 22, 15, 24, 17, 26, 19, 27, 21, 25, 23]
[25, 23, 27, 21, 26, 19, 24, 17, 22, 15, 20, 13, 18, 11, 16, 9, 14, 7, 12, 5, 10, 3, 8, 1, 6, 2, 4]
[2, 4, 1, 6, 3, 8, 5, 10, 7, 12, 9, 14, 11, 16, 13, 18, 15, 20, 17, 22, 19, 24, 21, 26, 23, 27, 25]
[27, 25, 26, 23, 24, 21, 22, 19, 20, 17, 18, 15, 16, 13, 14, 11, 12, 9, 10, 7, 8, 5, 6, 3, 4, 1, 2]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27]

Have fun golfing!

Is it fine to generate the original range at the front?

I think there's an error in the last line in the example. It should be 1 2 3 4 5, not 1 2 4 3 5.

Can anyone confirm that element 0 will only ever be 1 at the start and end of the process?

If we're returning an array of delimited strings, does the delimiter need to be consistent or could it alternate? (e.g., 1,2 3,4 5,6 7,8 9)

@RobertoGraham I have a python script that verifies that array[0] will only be 1 at the start and end of the process up to n = 999. From looking at the pattern, it seems like for every odd n, the first element goes 1, n-1, 3, n - 3, 5, n - 5, 7... up until n - 2, 3, n, 1, which will always take n steps. I don't see any reason that this pattern would change with larger n.

If we want to prove that the period is n when n is odd, it's probably easier to track where the element 1 goes: it follows the path 1, n, 2, n-2, 4, n-4, 6, n-6, 8, n-8, ... and it's easy to show by induction that an element at even position x moves to n-x after one step, and an element at odd position x moves to n-x+2. So if n=2k+1, then after the 2k-th step 1 will be be at 2k, and on the next step at n-2k = 1.

TI-Basic (83 series), 58 57 54 bytes (104 characters)
:seq(I,I,1,Ans→A
:Ans→B
:Repeat prod(Ans=ᶫB
:ᶫB→C
:int(⁻Ans/2→D
:SortD(ᶫC,ᶫA
:SortD(ᶫD,ᶫA
:Pause ᶫA
:End

Explanation
Takes input in Ans (e.g., write 5:prgmNAME to use lists of size five).
Creates three auxiliary lists of the given size (which are recreated from ᶫB at each step): ᶫB = ᶫC = {1,2,3,4,5,...} and ᶫD = {-1,-1,-2,-2,-3,...}. At each step, sorts ᶫC and ᶫD in descending order, applying the same permutation to ᶫA. In the case of ᶫC, this reverses ᶫA, and in the case of ᶫD, this swaps adjacent pairs because TI-Basic uses a really stupid selection sort implementation for SortD( which reorders as many identical elements as it possibly can. When ᶫA is equal to ᶫB again, we stop.
No, seriously, their built-in sorting algorithm is my second-biggest complaint with the TI-Basic interpreter. (My biggest complaint is how lots of nested loops slow down the interpreter, since the loop data is stored in a stack, but the stack is grown from the wrong end, so the calculator has to move the entire stack every time an element is pushed or popped.) But this time, it's convenient.

-1 byte: Pause stores the value it's printing to Ans, which is shorter to reference than ᶫA.
-3 bytes: take input in Ans

Awesome trick with the selection sort!

Jelly, 10 bytes
RµUs2UFµÐĿ

Try it online!
Explanation
RµUs2UFµÐĿ  Main link
R           Generate the range
        ÐĿ  While the results are unique (collecting results)
 µUs2UFµ    Reverse and reorder
  U         Reverse
   s        Slice non-overlapping into length
    2       2
     U      Reverse (automatically vectorizes to depth 1)
      F     Flatten

Note
If the original range needs to be at the end, append ṙ1 to the code for 12 bytes.

Alternate approach, same byte count

@DJMcMayhem Cool, nice!

05AB1E, 13 11 bytes
LIGÂ2ôí˜})Ù

Try it online!
Explanation
L             # range [1 ... input]
 IG           # input-1 times do:
   Â          # bifurcate
    2ô        # split into pieces of 2
      í       # reverse each
       ˜      # flatten
        }     # end loop
         )    # wrap stack in a list
          Ù   # remove duplicates

JavaScript (ES6), 89 85
Edit 4 bytes saved thx @JustinMariner
Using the fact that when any element is at the right place, all elements are.
n=>{for(l=[];n;l[n-1]=n--);while(alert(l=l.reverse().map((x,i)=>l[i^1]||x)),l[0]-1);}

Less golfed
n => {
  for(l=[], i=0; i<n; l[i] = ++i);
  while( alert(l=l.reverse().map( (x,i) => l[i^1] || x)),
         l[0]-1);
}

Test

var F=
n=>{for(l=[];n;l[n-1]=n--);while(alert(l=l.reverse().map((x,i)=>l[i^1]||x)),l[0]-1);}

alert=x=>console.log(x+'') // to avoid popup stress

function update() {
  F(+I.value);
}

update()
<input type=number id=I value=1 min=1 oninput='update()'>

I think you can shorten your range-building loop to for(l=[];n;l[n-1]=n--);, Try it online!.

@JustinMariner wow backwards, great! Thanks

R, 109 95 94 79 74 62 bytes
If the fact that the code throws warnings on top of the actual solution (no warnings if n is 1, 3 warnings if n is even and n warnings if n is odd) is not an issue, then the following works similarly to the previous solution, thanks to vector recycling:
n=scan();m=1:n;w=0:n+2*1:0;while(print(m<-rev(m)[w[w<=n]])-1)n

Try it online!
Thanks again to @Giuseppe for an extra 12 bytes off!
Previous, warning-less solution at 94 bytes:
n=scan();m=s=1:n;while(any(print(m<-rev(m)[c(if(n>1)2:1+rep(seq(0,n-2,2),e=2),n[n%%2])])!=s))n

Try it online!
Original solution at 109 bytes:
n=scan();m=s=1:n;repeat{cat(m<-rev(m)[c(t(embed(s,min(n,2))[!!s[-n]%%2,]),n[n%%2])],"\n");if(all(m==s))break}

Try it online!

88 bytes -- print returns its argument so we can take advantage of it here. I don't think I'd ever seen encode before; that's a neat way of indexing!

Thanks! Though i will need to make it a tiny bit longer as it doesn't work if n=1 so far.

Oh, I didn't notice that...replace 2 in embed with min(n,2)?

Yes that's what i had in mind

you can just put n instead of {} for the while loop since n doesn't do anything. :)

Impressive improvement!!! 0:n+2*1:0 is the same as 1+0:n+c(1,-1) for -4 bytes. any(print(...) != s) is equivalent to any(print(...)-s) for -1 byte. Aaand if we can prove that m[1]==1 only at the end of the algorithm, then we can drop the any, so we get while(print(...)-1) and we can remove s, so we get 62 bytes, n=scan();m=1:n;w=0:n+2*1:0;while(print(m<-rev(m)[w[w<=n]])-1)n

Mathematica, 142 bytes
(h=Range@#;W={};For[i=1,i<=#,i++,s=Reverse@h;AppendTo[W,h=Join[f=Flatten[Reverse/@Partition[s,{2}]],s~Complement~f]];s=h];DeleteDuplicates@W)&

Japt, 20 18 15 12 bytes
õ
£=ò2n)ÔcÃâ

Try it (-R flag for visualisation purposes only)
1 byte saved thanks to ETHproductions.
               :Implicit input of integer U
õ              :Range [1,U]
\n             :Reassign to U
£              :Map
  ò            :  Partitions
   2           :    Of length 2
    n          :    Starting from the end
     )         :  End partition
      Ô        :  Reverse
       c       :  Flatten
 =             :  Reassign to U
        Ã      :End map
         â     :Deduplicate

As of just now, I believe w ò mw can be ò2n)w

Oo, nice one, thanks, @ETHproductions. About to walk into the pub so I'll have a proper look at that in the morn'.

Husk, 9 bytes
U¡ȯṁ↔C2↔ḣ

Try it online!
            -- implicit input N                 |  3
         ḣ  -- list [1..N]                      | [1,2,3]
 ¡(     )   -- iterate the following function,  | [[1,2,3],[2,3,1],[3,1,2],[1,2,3],...
U           -- until the first repetition:      | [[1,2,3],[2,3,1],[3,1,2]]
       ↔    --   reverse                        |   [3,2,1]
     C2     --   cut into two                   |   [[3,2],[1]]
   ṁ↔       --   reverse each pair & flatten    |   [2,3,1]

JavaScript (ES6), 79 bytes
f=(n,a=[...Array(n)],b=a.map((x,i)=>n-((x?x-1:i)^1)||1))=>b[0]>1?b+`
`+f(n,b):b

Outputs a list for each step.
Note that we don't need to initialize the array to get the ball rolling.  If uninitialized (x is undefined), we can use the array's indices (parameter i) to do the first step:
b=a.map((x,i)=>n-((x?x-1:i)^1)||1)

Test Cases:

f=(n,a=[...Array(n)],b=a.map((x,i)=>n-((x?x-1:i)^1)||1))=>b[0]>1?b+`
`+f(n,b):b

console.log(f(1));
console.log(f(2));
console.log(f(3));
console.log(f(4));
console.log(f(5));
console.log(f(7));
console.log(f(27));

Ruby, 64 57 52 50 bytes
->x{(s=*w=1..x).map{s=w.map{|y|s[-y^1]||s[0]}}|[]}

Try it online!
How it works:
First create the range, then repeat the permutation x times: use a negative index, but flip the last bit, so we get the sequence -2, -1, -4, -3... if x is even, this will end well, if not we will add the remaining element at the end. Last step: filter out repeated arrays (so we cover all cases: x=1, x=2, odd and even numbers)

Haskell, 75 74 bytes
g(a:b:c)=b:a:g c
g x=x
h=g.reverse
0!x|x<[2]=[x]|1<2=x:0!h x
p n=0!h[1..n]

Try it online!
g does the pair-wise swaps, h a single step (reverse + reorder), ! repeatedly applies h (and collects the intermediate results) until the order is restored. Note: ! takes the additional but unused extra parameter 0 just to make it an infix operator. The main function p starts it up.
Edit: Thanks to @Angs for a byte.

0!x instead of f x saves a byte - Try it online!

Stax, 17 bytes
âΩÄ─g╫B♥C╛♠ƒ?|πcD

Run and debug it
Explanation
RX~Wr2/{r+}Fc|uPcx=C      # Full program, unpacked, implicit input
RX~                       # Create range, save to X register, pop back to input stack
   W                      # Start while loop until truthy value
    r                     # reverse array
     2/                   # Split into groups of 2
      {r+}F               # Loop through each set and reverse each
           c              # Copy top value
            |u            # Convert to string representation of array
              P           # Pop top value off
               cx=        # Copy top value, get value of x register, compare to top value
                  C       # If top value is truthy, cancel block and end

Suprised it works as fast as it does, tested up to 399 before I didn't want to temp my browser anymore.

Python 2, 165 159 138 81 bytes
x=input()+1
b=a=range(1,x)
while b:b=[b[x-min(x,i+1^1)]for i in a];print b;b*=a<b

Try it online!
-20 bytes thanks to @ChasBrown. (Sigh, I made a whole challenge about extended slicing syntax)
Whoa! GolfStorm (-57 bytes)! Thanks to Ian Gödel, tsh, and Jonathan Frech.

Instead of list(reversed(a)) try a[::-1].

' '*[2-(x<3),x][x%2]

132 bytes

128 bytes by removing an unnecessary variable

88 bytes

@tsh [b,0][b==a] -> b*(a!=b).

@JonathanFrech then b*=a!=b, 82 bytes

@tsh Or even a<b.

@JonathanFrech 81 bytes now

Java 8, 215 214 bytes
import java.util.*;n->{Stack a=new Stack(),t;int i=0;for(;i<n;a.add(++i));t=(Stack)a.clone();Collections x=null;for(i=0;i<1|!a.equals(t);System.out.println(t))for(x.reverse(t),i=0;i<n;i++)if(i<n-1)x.swap(t,i,++i);}

I tried to golf it using actual arrays instead of a List, but both reversing and swapping will take up too many bytes.. Maybe it can be combined in one loop (instead of first reversing, then swapping), but I've yet to figure this out.
This can definitely be golfed some more, though.
Explanation:
Try it here.
import java.util.*;           // Required import for Stack and Collections

n->{                          // Method with integer parameter and no return-type
  Stack a=new Stack(),        //  Original List
        t;                    //  Copy-List
  int i=0;                    //  Index-integer, starting at 0
  for(;i<n;a.add(++i));       //  Fill the original list with the integers
  t=(Stack)a.clone();         //  Make a copy of the List
  Collections x=null;         //  Static `Collections` to reduce bytes
  for(i=0;                    //  Reset index `i` to 0
      i<1                     //  Loop (1) as long as `i` is 0 (the first iteration),
      |!a.equals(t);          //  or the input array is not equal to the copy
      System.out.println(t))  //    After every iteration: print the modified List
    for(x.reverse(t),         //   Reverse the copied List
        i=0;                  //   Reset `i` to 0
        i<n;                  //   Inner loop (2) over the List
        i++)                  //     After every iteration: increase `i` by 1 again
      if(i<n-1)               //    Unless it's the last item in the List:
        x.swap(t,i,++i);      //     Swap the items at indexes `i` and `i+1`
                              //     (by increasing `i` by 1 first with `++i`)
                              //   End of inner loop (2) (implicit / single-line body)
                              //  End of loop (1) (implicit / single-line body)
}                             // End of method

Java (OpenJDK 8), 257 245 243 226 206 205 bytes
n->{int i=0,k,t[]=new int[n];while(i<n)t[i]=++i;do{for(i=0;i<n/2;t[i]=t[n+~i],t[n+~i++]=k)k=t[i];for(k=1;k<n;t[k]=t[--k],t[k]=i,k+=3)i=t[k];System.out.println(java.util.Arrays.toString(t));}while(t[0]>1);}

Try it online!

n->{java.util.Arrays x=null;int i=0,k,f,a[]=new int[n],t[]=new int[n];for(;i<n;a[i]=t[i]=++i);do{for(f=0;f<n/2;k=t[f],t[f]=t[n+~f],t[n+~f++]=k);for(k=1;k<n;t[k]=t[--k],t[k]=f,k+=3)f=t[k];System.out.println(x.toString(t));}while(!x.equals(a,t));} (245 bytes) Summary of changes: java.util.Arrays x=null;; n-f-1 to n+~f; removed brackets of loop; Changed 2x k-1 to --k (and also changed k+=2 to k+=3 to neutralize this.

And you can save two more bytes by removing ,f and re-using i.

Nice, you've improved it a lot! You're now even lower than my Java answer. :) You can golf one more byte by changing for(i=0;i<n/2;k=t[i],t[i]=t[n+~i],t[n+~i++]=k); to for(i=0;i<n/2;t[i]=t[n+~i],t[n+~i++]=k)k=t[i];

MATL, 17 bytes
:`tP2ePXz!tG:-a]x

Try it online!
Explanation
:       % Implicit input: n. Push [1 2 ... n]
`       % Do...while
  t     %   Duplicate
  P     %   Reverse
  2e    %   Reshape into a 2-row matrix. A final 0 is added if needed
  P     %   Reverse each column
  Xz    %   Nonzero entries (i.e. remove final 0 if present). Gives a column vector
  !     %   Transpose into a row
  t     %   Duplicate
  G:    %   Push [1 2 ... n] again
  -     %   Subtract element-wise
  a     %   Any. Gives true if there is at least a nonzero value
]       % End. Go to next iteration if top of the stack is true.  So the loop ends
        % when [1 2 ... n] has been found again
x       % Delete top of the stack (which is [1 2  ... n]). Implicit display

GolfScript, 33 bytes
Nope, I can't simplify the algorithm.
~),1>:a{-1%2/{-1%}%{+}*.p.a=!}do;

Try it online!
Explanation
~                                 # Dump the input
 ),                               # Generate inclusive range: 0 -> input
   1>:a                           # Set [1 2 ... input-1 input] to a without popping
       {                     }do  # Do ... While
                         .a=!     # The current item does not equal to a
        -1%                       # Reverse the item
           2/                     # Split into equal parts of 2
             {-1%}%               # For each equal part, reverse
                   {+}*           # Flatten the list
                       .p         # Print the list
                                ; # We don't need to implicit output the
                                  # extra value left on the stack

Vyxal 3 j, 8 bytes
ɾᶨλṚ2ẆVf

Try it Online!

JavaScript (ES6), 122 bytes
f=(n,a=[...Array(n)].map((_,i)=>i+1),r=[],b=a.map((_,i)=>a[n+~(i^1)]||a[0]))=>b.some((e,i)=>e>b[i+1],r.push(b))?f(n,b,r):r

r.push(a) could be used instead of r.push(b) to put the original permutation at the front.

Haskell, 97 bytes
This feels a bit long :(
f n|x<-[1..n]=x:takeWhile(/=x)(tail$iterate((r=<<).g.r)x)
r=reverse
g[]=[]
g x=take 2x:g(drop 2x)

Try it online!
Explanation/Ungolfed
-- starting with x, accumulate the results of repeatedly
-- applying the function permute
f n = x : takeWhile (/=x) (tail $ iterate permute x)
  where x = [1..n]
        -- reverse, cut2, reverse each pair & flatten
        permute = concatMap reverse . cut2 . reverse

-- recursively transform a list into groups of 2
cut2 [] = []
cut2 xs = take 2 xs : g (drop 2 xs)

Stacked, 42 bytes
[~>[rev 2#<$revflatmap]periodsteps behead]

Try it online!
Performs the given transformation using the periodsteps builtin. However, this builtin returns all of the elements, which includes the input's range as its first and last elements. We therefore behead the list, returning all but the first element.

AWK, 123 bytes
Not very tight, but this is the best I could come up with.
{for(N=$1;N>$i=++i;);for(;n++<(i%2?i:i>2?2:1);){for(k=0;k++<i;)K[k]=(z=i-k+(k-1)%2*2)?$z:$1;for(k=0;k++<N;){$k=K[k]}print}}

Try it online!

JavaScript, 136 bytes
(n)=>{for(a=[],i=0;i<n;a[i]=++i);for(j=0;j<(n&1?n:2);j++){a.reverse();for(i=0;i<a.length-1;i += 2)m=a[i],a[i]=a[i+1],a[i+1]=m;alert(a)}}

TypeScript’s type system, 203 193 190 183 bytes
//@ts-ignore
type F<N,A=[],E=A,O=N,G=[...N,...A]>=N extends[1,...infer D]?F<D,[N,...A]>:A extends[...infer R,infer X,infer Y]?F<[...N,X,Y],R,E,O>:E extends O[any]?O:F<[],G,E,[...O,G]>

Try it at the TS playground
This is a generic type F, which takes input as a tuple type of 1s representing a unary number, and outputs a list of unary numbers in the same format.
I can’t believe I got this all to fit in a single type. This is definitely one of the coolest TS types submissions I’ve posted.
Explanation
The //@ts-ignore comment on the first line tells the compiler to suppress any warnings from the following line.
The beginning of the type describes its arguments:
type F<N,A=[],E=A,O=N,G=[...N,...A]>

What the arguments do is explained later, but you should know that G is an alias for N with A appended to it; it comes in handy later.
The type has three “stages”, which are entered at different times in the evaluation of the type.

The first stage converts the unary number to the range of unary numbers between 1 and the input. (At this stage, the input is in N, and A is the empty tuple.)
N extends[1,...infer D]

Is the first item of N a one? If so, remove it and call the rest D, and…
F<D,[N,...A]>

…recurse, with N set to D, and with N prepended to A.
By the end of stage 1, A will contain the range from 1 to the input, E will be set equal to A, and N and O will both be the empty tuple.
(E is the initial step; this will be how the type knows to terminate. O will be the list of intermediate results, which will be the final return value.)

If the first stage was not entered, because N is either empty or contains elements that aren’t ones, then the second stage is entered, to reverse and reorder the elements of A.
A extends[...infer R,infer X,infer Y]

If A has two or more items, call the last two X and Y respectively, and the rest R.
F<[...N,X,Y],R,E,O>

Recurse, appending X and Y to N, setting A to R, and keeping the values of E and O as they already are.
By the end of this stage, N will contain the reversed and reordered items of A. A will be empty if it originally had an even number of items, but if its length was odd then it will contain the last item to be appended to N. This is a minor pain point of the solution, adding 14 bytes to alias G to N with A appended.

The third stage does the “repeat” step.
E extends O[any]?O

If E (the initial result) is contained in O (the list of intermediate results), then the program is finished; return O.
F<[],G,E,[...O,G]>

Otherwise, recurse with N set to the empty tuple (skipping stage 1 and going straight to stage 2), A set to G (the alias for N with A appended), E left unchanged, and O with G appended.

Perl 5 -p, 89 bytes
$_=$;=join$",1..$_;do{$_=join$",reverse/\d+/g;s/(\d+) (\d+)/$2 $1/g;$\+=say}until$;eq$_}{

Try it online!


text:
Creepy Corridors
This challenge is inspired by a board game I played some time ago.
The story of this challenge doesn't necessarily have to be read, the goal of the challenge-section should explain everything necessary.
The Story
People are locked inside a large room with a human-devouring monster. The walls of the room are enchanted, teleporting objects across the room when touched. Said monster marches across the room, hunting for flesh. The first human in its sight will be consumed by its sharp teeth.
The Goal of the Challenge
You are given the map of the room, including the people's and the monster's location.
%%%KLMNOPQRSTA%
%%J           B
%I       %    C
H             D
G   %%        E
F             F
E      %      G
D             H
C   %        I%
B           J%%
%ATSRQPONMLK%%%

Let's break down the components of the map.

Letters from A to T: If the monster steps onto one of these, it will be teleported to this letter's second appearance and not change its direction. There will only ever be zero or two of any letter on the board.
%: Wall tiles. Just for formatting & nice looks.
#: The monster's starting location.
*: The people's locations.
 : Empty tiles, the monster can move freely on them.

Some additional things to note about the map:

The map dimensions and object location will not be constant, so your code will have to dynamically adapt to that.

The monster will always go in the direction that it currently facing (facing west at the start) unless it spots a human, in which case it will turn towards the closest human.
The monster spots a human if there are no wall or teleporter tiles in a straight horizontal or vertical line between it and the human.
Another thing to note is that if the monster is in front of a solid wall (%) or has to decide between two humans, it will always prioritize right over left.
If the monster is not able to turn right and make a step forwards for some reason, it will turn left instead.
So, in the end, the order that the monster prioritizes directions would we forward, right, left, backwards.
Input

The map, including the monster's starting location and the people's positions as their respective characters. There should not be any other input than the map string, or the array of strings, or characters.

The input may be received in any reasonable format; a single string or an array of strings for the map.
Output
The coordinate of the person that first gets eaten by the monster.
The coordinates start from the top-left corner and are 0-indexed, so the first tile will have the coordinates (0|0). If you are using 1-indexing, please specify it in your answer.
Rules

This is code-golf, the shortest code in bytes in any language wins.
Standard loopholes are forbidden.
You may assume that the monster will always be able to reach a human.

Test Cases
Input:
%%%KLMNOPQRSTA%
%%J           B
%I       %*   C
H   *         D
G   %%        E
F       #     F
E      %      G
D      *      H
C   %        I%
B           J%%
%ATSRQPONMLK%%%

Output: (10,2), since the monster cannot see the two other people when it runs past them, it gets teleported to the other F wall, where it will then see the last person.
Input:
%%%KLMNOPQRSTA%
%%J           B
%I      *     C
H     %%%   * D
G      #%     E
F     %%%   % F
E             G
D       %     H
C       *    I%
B       *   J%%
%ATSRQPONMLK%%%

Output: (12,3)
Input:
%%%KLMNOPQRSTA%
%%J           B
%I     %%%    C
H     *%#%    D
G             E
F             F
E       %     G
D             H
C            I%
B           J%%
%ATSRQPONMLK%%%

Output: (6, 3)
Input:
%%%%%%%%%%%%%%%
%#%       %%% %
%A%ABCD   %*% %
%*F     G %%% %
% %BC% FD     %
% %   %    %%%%
% %  %       %%
%   % %%   G  %
%             %
%*%    %    % %
%%%%%%%%%%%%%%%

Output: (1,9)

Good luck!

You should state, explicitly and early in the description, that the humans don't move. I didn't realize at first that they are stationary. If I were a human in that situation, I'd certainly be moving!

Python 2, 565 .. 422 4451 .. 444 4632 .. 468 467 463 bytes
u,U='*%'
G=lambda s:u==s.strip('# ')[0]and len(N)-s.find(u)
b=input()
D=3;j=''.join;N,w,P,t,B=j(b),len(b[0]),[0,1,0,-1],{},map(j,zip(*b))
for c in N:
 l,r=N.find(c),N.rfind(c)
 if u<c:t[l]=r;t[r]=l
 if'#'==c:x,y=l%w,l/w
while u!=b[y][x]:
 O=[B[x][y-1::-1],b[y][x+1:],B[x][y+1:],b[y][x-1::-1]];L,R=O[D-1],O[~D]
 if u<b[y][x]:X=t[x+w*y];x,y=X%w,X/w
 elif(G(O[D])<1)*(G(R)+G(L)+(U==O[D][0])):D-=0<G(L)>G(R)or(U==R[0])*-~(U==L[0])or-1;D%=4
 x+=P[D];y+=P[~D]
print x,y

Try it online!
Saved a lot of bytes thanks to Halvard, Ian and Jonathan
1: Got longer, in order to fix the case of turning twice, and to find the location of the monster.

2: Got even longer.. Monster shouldn't change direction on when teleporting.

Somewhat golfed to 482 bytes. Shortened link due to TIO being to long

@Halvard A small golf, just 1 byte: 481

l.replace('#',' ') -> l.replace(*"# ").

Fixed, but now it's the same length as yours, 434 bytes

Aren't the parenthesis redundant, 431 bytes?

418 bytes.

I'm afraid finding the location of the monster is part of the challenge.. Just verified with OP, because I also thought the wording regarding the input was a bit odd.. You should only input the map itself.

@KevinCruijssen I know Ian said my answer counts as valid, but I'll change it anyway.

@TFeld Was about to make a comment to Ian saying either the Python answer should be modified, or the rules should be changed. He can't make an exclusion for one answer. But I see you've already made that decision yourself. Nice answer btw, +1 from me! I'm always having loads of trouble with 2D challenges, especially when they have teleports and turn-arounds like this one. Then again, I primarily codegolf in Java, which is unsuitable for most codegolf challenges in general, but especially for 2D challenges in my experience. ;)

if(x+y*w in t): ->  if x+y*w in t:.

@KevinCruijssen: Don't be afraid of the 2-D challenges. A hint for you, if you would like it: one thing that helps hugely are complex numbers. Do you want to move? Add them up. Difference of coordinates? Subtract them. Distance? Take absolute value of the difference. Do you want to turn right, left and so on? Just multiply by i or -i. And so on. (And no, this is definitely not an advertisement of my own answer :—))

(L[0]==U==R[0])+(U==R[0]) -> (R[0]==U)*-~(L[0]==U).

Perl 6, 343 334 333 328 322 308 bytes
{my \m=%((^@^a X ^@a[0]).map:{.[0]i+.[1]=>@a[.[0]][.[1]]});my \a=m<>:k.classify
({m{$_}});my$m=a<#>[0];my$d=-1;{$d=($d,i*$d,-i*$d,-$d).min({$^q;first ?*,map
{(((my \u=m{$m+$_*$q})~~"%")*(1+!($_-1))+(u~~"A".."Z"))*m+(u~~"*")*$_},^m});
$m+=$d;$m=$d+(a{m{$m}}∖~$m).pick while m{$m}~~"A".."Z"}...{m{$m}~~"*"};$m}

Try it online!
(There are no newlines in the actual code. I inserted them just to wrap the lines for easier reading.)
This is unable to deal with maps where it is possible to see outside of the map bounds. (I. e. maps with empty spaces at the border.) If this matters, +5 bytes. But, since the teleporters block LoS now, it shouldn't.
Explanation: It's a function which takes the map as a list of lists of characters. Let's break it down into statements:
my \m=%((^@^a X ^@a[0]).map:{.[0]i+.[1]=>@a[.[0]][.[1]]});: Let's make a hash ("dictionary" for Pythonists) called m (it's a sigilless variable, so we need to be explicit about assigning a hash into it with %(...)) which associates complex keys of form x+iy with characters which are in the yth rown and xth column of the map.
my \a=m<>:k.classify({m{$_}});: This makes an "inverse dictionary" of m, called a: there is one key corresponding to each value in m, and the value is a list of complex coordinates (keys in m) that contain that character. So, for instance a{"#"} will give a list of all coordinates where there is a # on the map. (This is also a sigilless variable, but we're in luck since classify returns a hash.)
my$m=a<#>[0];my$d=-1: Set the initial monster position. We look up the # in the inverse hash a. We must use [0] since a<#> is still a list, even when it contains only 1 element. The $d contains the direction of monster; we set it to the West. (The direction is a complex number as well, so -1 is west.)
OK, the next statement is quite nasty. First, let's have a look at this: {$^q;first ?*,map {(((my$u=m{my$t=$m+$_*$q})~~"%")*(1+!($_-1))+($u~~"A".."Z"))*m+($u~~"*")*abs($t-$m)},^m} This is a routine that evaluates LoS in the given direction. If there is a human in this direction, it returns the distance to the human. If there is a wall or a teleport in this direction, it returns the total number of squares of the map. (The point is to give such a high number that it is greater than any legitimate distance to a human.) Finally, if the wall is in this direction and in distance 1, we return 2 × total number of squares of the map. (We want never ever be running through walls, so these need even a bigger score. We will be choosing the minimum shortly.)
We use this in the construct $d=($d,i*$d,-i*$d,-$d).min( LoS deciding block );. Since we use complex numbers for everything, we can easily get directions which are relative forward, right, left and backwards from the original direction just by multiplying it by 1, i, -i (remember that the y axis goes the other way that you may be used to from math) and -1, respectively. So we form the list of directions in this order, and find the direction which has the minimal "distance to a human" (according to the block above), which makes sure that any human beats any wall and anything beats a wall which is right under the monster's nose. We use the fact that the min function gives the first minimal value. If there is a tie in distance between several directions, the monster will prefer forward to right to left to backwards, which is exactly what we want. So we get a new direction which is then assigned to $d.
$m+=$d; just makes the monster step in the new direction.
$m=$d+(a{m{$m}}∖~$m).pick while m{$m}~~"A".."Z" takes care of the teleports. Let's say the monster is at a teleport A. First we search for A in the inverse hash %a and that turns up the two positions of the teleport A, then we discard the current position using the set difference operator (which looks like a backslash). Since there are exactly 2 occurences of each teleport on the map and the monster is surely standing on one, the difference will be a set with 1 element. We then use .pick to pick a random element (believe or not, but this is the shortest way to get the element of 1-element set :—)). This kind of thing happens until the monster ends up somewhere not in a portal.
Everything in the last 4 paragraphs describes one massive construction of form {change direction; step; handle teleports}...{m{$m}~~"*"}. This is a sequence that calls the block on the left of ... until the condition on the right of the ... is true. And that one is true when the monster is on a square with a human. The list itself contains return values of the huge block on the left, which is garbage (most likely (Any)) because it returns the value of the while loop at the end. Essentially, we use it as a cheaper while loop. The value of the list is discarded (and the compiler moans about a "useless use of ... in a sink contest", but who cares). When this all is done, we return $m — the monster's position after it found a human, still as a complex number (so, for the first test, we give 10+2i and so on).

Nice explanation! :)

This is priceless. Absolutely Brilliant and pure elegant explanation!

JavaScript (ES6), 258 245
g=>eval("m=g[I='indexOf']`#`,D=[w=g[I]`\n`+1,-1,-w,k=t=1],g=[...g];for(n=1/0;n;(o=g[m+=d=D[k]])>'@'?g[g[u=m]=t=1,m=g[I](o),u]=o:o<'%'?t=1:o<'*'&&(m-=d,k=k+t++&3))D.map((d,j)=>{for(q=0,u=m;g[u+=d]<'%';++q);g[u]=='*'&n>q&&(n=q,k=j)});[m%w,m/w|0]")

Less golfed
g=>{
    var u, // temp current position
        q, // distance so far scanning for a human
        o, // value of grid at current position
        d, // offset to move given current direction
        n = 1/0 // current distance from human
        m = g.indexOf(`#`), // monster position
        w = g.indexOf(`\n`)+1, // grid width + 1 (offset to next row)
        D = [w,-1,-w,1], // offset for moves, clockwise
        k = 1, // current direction, start going west
        t = 1; // displacement for turn
    g=[...g]; // string to array
    while (n) // repeat while not found (distance > 0)
    {
      // look around to find humans
      D.forEach( (d,j) => { // for each direction
        // scan grid to find a human
        for(q=0, u=m; g[u+=d]<'$'; ++q); // loop while blank space
        if ( g[u] == '*' // human found at position u
             & n>q ) // and at a shorter distance than current
        {
           n = q; // remember min distance
           k = j; // set current direction
        }
      })
      // if human found, the current direction is changed accordingly
      d = D[k] // get delta
      m += d // move
      o = g[m] // current cell in o
      if (o > '@') // check if letter (teleporter)
      {
        t = 1 // keep current direction, next turn will be right
        u = m // save current position in u
        g[u] = 1 // clear current cell, so I can find only the other teleporter
        m = g.indexOf(o) // set current position to other teleporter
        g[u] = o // reset previous cell content
      }
      else if (o > '%') // check if '*'
      {
        // set result, so we can exit the loop
        r = [ m%w, m/w|0 ] // x and y position
      }
      else if (o == '%') // check if wall
      {
        // turn
        m -= d // current position invalid, go back
        k = (k+t) % 4 // turn right 90° * t
        t = t+1 // next turn will be wider
      }
      else
      {
        t = 1 // keep current direction, next turn will be right
      }
    }
    return r
}

Test

var F=
g=>eval("m=g[I='indexOf']`#`,D=[w=g[I]`\n`+1,-1,-w,k=t=1],g=[...g];for(n=1/0;n;(o=g[m+=d=D[k]])>'@'?g[g[u=m]=t=1,m=g[I](o),u]=o:o<'%'?t=1:o<'*'&&(m-=d,k=k+t++&3))D.map((d,j)=>{for(q=0,u=m;g[u+=d]<'%';++q);g[u]=='*'&n>q&&(n=q,k=j)});[m%w,m/w|0]")

var grid=[`%%%KLMNOPQRSTA%\n%%J           B\n%I       %*   C\nH   *         D\nG   %%        E\nF       #     F\nE      %      G\nD      *      H\nC   %        I%\nB           J%%\n%ATSRQPONMLK%%%`
,'%%%KLMNOPQRSTA%\n%%J           B\n%I      *     C\nH     %%%   * D\nG      #%     E\nF     %%%   % F\nE             G\nD       %     H\nC       *    I%\nB       *   J%%\n%ATSRQPONMLK%%%'
,'%%%KLMNOPQRSTA%\n%%J           B\n%I     %%%    C\nH     *%#%    D\nG             E\nF             F\nE       %     G\nD             H\nC            I%\nB           J%%\n%ATSRQPONMLK%%%'
,'%%%%%%%%%%%%%%%\n%#%       %%% %\n%A%ABCD   %*% %\n%*F     G %%% %\n% %BC% FD     %\n% %   %    %%%%\n% %  %       %%\n%   % %%   G  %\n%             %\n%*%    %    % %\n%%%%%%%%%%%%%%%'
]
$(function(){
  var $tr = $('tr')
  grid.forEach(x=>{
    $tr.eq(0).append(""+x+"	")
    $tr.eq(1).append(""+F(x)+"	")
  })
})
td {padding: 4px; border: 1px solid #000; white-space:pre; font-family:monospace }

source: Stack Exchange

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

sort: votes


text:
Cyclotomic polynomial
Background (skip to definitions)
Euler proved a beautiful theorem about the complex numbers: \$e^{ix} = \cos(x) + i \sin(x)\$.
This makes de Moivre's theorem easy to prove:
$$
(e^{ix})^n = e^{i(nx)} \\
(\cos(x) + i\sin(x))^n = \cos(nx) + i\sin(nx)
$$
We can plot complex numbers using the two-dimensional Euclidean plane, with the horizontal axis representing the real part and the vertical axis representing the imaginary part. This way, \$(3,4)\$ would correspond to the complex number \$3+4i\$.
If you are familiar with polar coordinates, \$(3,4)\$ would be \$(5,\arctan(\frac 4 3))\$ in polar coordinates. The first number, \$r\$, is the distance of the point from the origin; the second number, \$\theta\$, is the angle measured from the positive \$x\$-axis to the point, counter-clockwise. As a result, \$3 = r \cos \theta\$ and \$4 = r \sin \theta\$. Therefore, we can write \$3+4i\$ as \$r \cos \theta + r i \sin \theta = r(\cos \theta + i \sin \theta) = re^{i\theta}\$.
Let us solve the complex equation \$z^n = 1\$, where \$n\$ is a positive integer.
We let \$z = re^{i\theta}\$. Then, \$z^n = r^ne^{in\theta}\$. The distance of \$z^n\$ from the origin is \$r^n\$, and the angle is \$n\theta\$. However, we know that the distance of 1 from the origin is 1, and the angle is \$\theta\$. Therefore, \$r^n=1\$ and \$n\theta=\theta\$. However, if you rotate by \$2π\$ more, you still end up at the same point, because \$2π\$ is just a full circle. Therefore, \$r=1\$ and \$n\theta = 2kπ\$, giving us \$z=e^{2ikπ / n}\$.
We restate our discovery: the solutions to \$z^n=1\$ are \$z=e^{2ikπ / n}\$.
A polynomial can be expressed in terms of its roots. For example, the roots of \$x^2-3x+2\$ are 1 and 2, so \$x^{2}-3x+2 = (x-1)(x-2)\$. Similarly, from our discovery above:
$$z^n-1 = \prod^{n-1}_{k=0} (z-e^{2ik\pi / n})$$
However, that product certainly contained roots of other n. For example, take \$n=8\$. The roots of \$z^{4}=1\$ would also be included inside the roots of \$z^{8}=1\$, since \$z^{4}=1\$ implies \$z^{8} = (z^{4})^{2} = 1^{2} = 1\$. Take \$n=6\$ as an example. If \$z^{2}=1\$, then we would also have \$z^{6}=1\$. Likewise, if \$z^{3}=1\$, then \$z^{6}=1\$.
If we want to extract the roots unique to \$z^{n}=1\$, we would need \$k\$ and \$n\$ to share no common divisor except \$1\$. Or else, if they share a common divisor \$d\$ where \$d>1\$, then \$z\$ would be the \$\frac k d\$-th root of \$z^{n / d}=1\$. Using the technique above to write the polynomial in terms of its roots, we obtain the polynomial:
$$\prod_{\substack{0 \le k < n \\ \gcd(k,n) = 1}} (z - e^{2ik\pi / n})$$
Note that this polynomial is done by removing the roots of \$z^{n / d}=1\$ with d being a divisor of \$n\$. We claim that the polynomial above has integer coefficients. Consider the LCM of the polynomials in the form of \$z^{n / d}-1\$ where \$d>1\$ and \$d\$ divides \$n\$. The roots of the LCM are exactly the roots we wish to remove. Since each component has integer coefficients, the LCM also has integer coefficients. Since the LCM divides \$z^{n}-1\$, the quotient must be a polynomial with integer coefficient, and the quotient is the polynomial above.
The roots of \$z^{n}=1\$ all have radius 1, so they form a circle. The polynomial represents the points of the circle unique to n, so in a sense the polynomials form a partition of the circle. Therefore, the polynomial above is the n-th cyclotomic polynomial. (cyclo- = circle; tom- = to cut)
Definition 1
The n-th cyclotomic polynomial, denoted \$\Phi_n(x)\$, is the unique polynomial with integer coefficients that divide \$x^{n}-1\$ but not \$x^{k}-1\$ for \$k < n\$.
Definition 2
The cyclotomic polynomials are a set of polynomials, one for each positive integer, such that:
$$x^n - 1 = \prod_{k \mid n} \Phi_k(x)$$
where \$k \mid n\$ means \$k\$ divides \$n\$.
Definition 3
The \$n\$-th cyclotomic polynomial is the polynomial \$x^{n}-1\$ divided by the LCM of the polynomials in the form \$x^{k}-1\$ where \$k\$ divides \$n\$ and \$k < n\$.
Examples

\$Φ_{1}(x) = x - 1\$
\$Φ_{2}(x) = x + 1\$
\$Φ_{3}(x) = x^{2} + x + 1\$
\$Φ_{30}(x) = x^{8} + x^{7} - x^{5} - x^{4} - x^{3} + x + 1\$
\$Φ_{105}(x) = x^{48} + x^{47} + x^{46} - x^{43} - x^{42} - 2x^{41} - x^{40} - x^{39} + x^{36} + x^{35} + x^{34} + x^{33} + x^{32} + x^{31} - x^{28} - x^{26} - x^{24} - x^{22} - x^{20} + x^{17} + x^{16} + x^{15} + x^{14} + x^{13} + x^{12} - x^{9} - x^{8} - 2x^{7} - x^{6} - x^{5} + x^{2} + x + 1\$

Task
Given a positive integer \$n\$, return the \$n\$-th cyclotomic polynomial as defined above, in a reasonable format (i.e. e.g. list of coefficients is allowed).
Rules
You may return floating point/complex numbers as long as they round to the correct value.
Scoring
This is code-golf. Shortest answer in bytes wins.
References

Wolfram MathWorld
Wikipedia

Maybe add 105 as a test?

@JonathanAllan I don't want to type 48 terms

In definition 2, is the "positive integer" x, n or k?

@H.PWiz The notation is same as definition 1

@LeakyNun, Thanks. Just trying to wrap my head around this.

Related

Could someone double check the coefficients of the 105 test case? (not using Wikipedia that is...)

@JonathanAllan The Haskell solution gives the same result.

Are floating-point inaccuracies allowed?

@miles I hate floats with a passion >.< but I'll defend to the death your right to use floats.

@LeakyNun Is it OK if the floats are complex numbers, in addition to having inaccuracies?

@xnor I hate complex numbers with a passion >.< but I'll defend to the death your right to use complex numbers.

May our polynomial have extra leading zeroes?

May we output complex floating point numbers as long as they yield the correct answer when rounded to the nearest integer/gaussian integer?

@fireflame241 yes

Haskell, 120 bytes
import Data.Complex
p%a=zipWith(\x y->x-a*y)(p++[0])$0:p
f n=foldl(%)[1][cis(2*pi/fromInteger n)^^k|k<-[1..n],gcd n k<2]

Try it online!
Gives a list of complex floats that has entries like 1.0000000000000078 :+ 3.314015728506092e-14 due to float inacurracy. A direct method of multiplying out to recover the polynomial from its roots.

The fromInteger is a big concession to Haskell's type system. There's got to be a better way. Suggestions are welcome. Dealing with roots of unity symbolically might also work.

Haskell, 127 bytes
(h:t)%q|all(==0)t=[]|1>0=h:zipWith(\x y->x-h*y)t q%q
f n=foldl(%)(1:(0<$[2..n])++[-1])[tail$f k++[0,0..]|k<-[1..n-1],mod n k<1]

Try it online!
No imports.
Uses the formula

Computes Φ_n(x) by dividing the LHS by each of the other terms in the RHS.
The operator % does division on polynomials, relying on the remainder being zero. The divisor is assumed to be monic, and is given without the leading 1, and also with infinite trailing zeroes to avoid truncating when doing zipWith.

[0,0..] is a byte shorter than repeat 0.

@flawr Divides polynomials. I think it's the same method as your solution.

It looks damn elegant, I'm gonna have to get a closer look tomorrow:)

this answer makes me want to learn Haskell.

@xnor -1 byte

Mathematica, 43 41 bytes
Factor[x^#-1]/Times@@#0/@Most@Divisors@#&

Of course, we can always use the built-in, but if we don't, this divides xn-1 by Φk(x) (computed recursively) for every proper divisor k of n.
We use Factor to get a polynomial at the end. I think the reason this works is that x^#-1 factors into all the cyclotomic polynomials of divisors of n, and then we divide out the ones we don't want.
-2 bytes thanks to Jenny_mathy, rewriting the Factor to only apply to the numerator.

This is great! you can save a byte by using Factor@

@Jenny_mathy Doing that seems to parse as Factor[x^#-1]/Times@@... instead; if we didn't have brackets there, we'd want parentheses.

ok... but I have to say that when I tested it, it was giving the right results...

That's interesting. It means we can save another byte by writing it Factor[x^#-1]/Times@@..., and it also means I have no clue how it works.

MATL, 32 31 27 25 bytes
Z\"@:@/]XHxvHX~18L*Ze1$Yn

Output may be non-integer due to floating-point inaccuracies (which is allowed). The footer does rounding for clarity.
Try it online!

Haskell, 250 236 233 218 216 bytes
This is a verbose version, (@xnor can do it in almost half the score) but it is guaranteed to work for any n as long as you have enough memory, but it does not use a builtin for generating the n-th cyclotomic polynomial. The input is an arbitrary size integer and the output is a polynomial type with (exact) rational coefficients.
The rough idea here is calculatin the polynomials recursively. For n=1 or n prime it is trivial. For all other numbers this approach basically uses the formula from definition 2

solved for . Thanks @H.PWiz for quite a bunch of bytes!
import Math.Polynomial
import Data.Ratio
import NumberTheory
p=powPoly x
q=poly LE
c n|n<2=q[-1,1%1]|isPrime n=sumPolys$p<$>[0..n-1]|1>0=fst$quotRemPoly(addPoly(p n)$q[-1])$foldl1 multPoly[c d|d<-[1..n-1],n`mod`d<1]

For n=105 this yields following polynomial (I tidied up all the %1 denominators):
[1,1,1,0,0,-1,-1,-2,-1,-1,0,0,1,1,1,1,1,1,0,0,-1,0,-1,0,-1,0,-1,0,-1,0,0,1,1,1,1,1,1,0,0,-1,-1,-2,-1,-1,0,0,1,1,1]

The polynomial for n=15015 can be found here (the largest coefficient is 23).
Try it online!

+1 for not being a builtin.

@flawr Why are you using Rationals? It seems to work fine without them

Does it? I had problems with quotRemPoly, let me try again then!

Ah the "problem" was that it yields Double coefficients if you don't use Ratio Integer instead, which might cause problems for very (very) large n.

Eh... I don't think that's a problem.

Jelly, 23 bytes
R÷
ÆḌÇ€FQœ-@Ç×ı2×ØPÆeÆṛ

Try it online!
Outputs as a list of coefficients.
Has floating point AND complex inaccuracies. Footer does rounding to make output prettier.

J, 36 bytes
1+//.@(*/)/@(,.~-)_1^2*%*i.#~1=i.+.]

Try it online!
Uses the formula

There are some floating-point inaccuracies, but it is allowed.

Pari/GP, 8 bytes
A built-in.
polcyclo

Try it online!

Pari/GP, 39 bytes, without built-in
f(n)=p=x^n-1;fordiv(n,d,d<n&&p/=f(d));p

Using the formula:
\$ \Phi_n(x)=\dfrac{x^{n}-1}{\prod\limits_{\stackrel{d|n}{{}_{d<n}}}\Phi_{d}(x)} \$.
Try it online!

APL(Dyalog Unicode), 32 bytes SBCS
{(0,⍵)-⍺×⍵,0}/⍤⌽1,¯1*2×÷×1⍸⍤=⊢∨⍳

Try it on APLgolf!
Almost direct port of miles' J answer. Returns a polynomial as a vector of coefficients wrapped once, with higher-order terms on the right side.
{(0,⍵)-⍺×⍵,0}/⍤⌽1,¯1*2×÷×1⍸⍤=⊢∨⍳    ⍵←n
                         1⍸⍤=⊢∨⍳    Numbers coprime to ⍵
                  ¯1*2×÷×    Divide by ⍵, double, raise -1 to the power of them
{(0,⍵)-⍺×⍵,0}/⍤⌽1,    Evaluate the polynomial with the roots of the above

((0,⊢)-0,⍨×) saves a byte

Mathematica, 81 bytes
Round@CoefficientList[Times@@(x-E^(2Pi*I#/k)&/@Select[Range[k=#],#~GCD~k<2&]),x]&

R, 176 171 139 112 bytes
function(n){for(r in exp(2i*pi*(x=1:n)[(g=function(x,y)ifelse(o<-x%%y,g(y,o),y))(x,n)<2]/n))T=c(0,T)-r*c(T,0)
T}

Try it online!
Massively simpler version; uses a for loop rather than a Reduce.

CJam (52 51 bytes)
{M{:K,:!W+K,0-{K\%!},{j($,\:Q,-[{(\1$Qf*.-}*;]}/}j}

Online demo. This is an anonymous block (function) which takes an integer on the stack and leaves a big-endian array of coefficients on the stack.
Dissection
{                    e# Define a block
  M{                 e#   Memoised recursion with no base cases.
    :K,:!W+          e#     Store argument in K and build (x^K - 1)
    K,0-{K\%!},      e#     Find proper divisors of K
    {                e#     Foreach proper divisor D...
      j              e#       Recursive call to get Dth cyclotomic poly
      ($,\:Q,-       e#       The cleverest bit. We know that it is monic, and the
                     e#       poly division is simpler without that leading 1, so
                     e#       pop it off and use it for a stack-based lookup in
                     e#       calculating the number of terms in the quotient.
                     e#       Ungolfed this was (;:Q1$,\,-
                     e#       Store the headless divisor in Q.
      [              e#       Gather terms into an array...
        {            e#         Repeat the calculated number of times...
          (\         e#           Pop leading term, which goes into the quotient.
          1$Qf*.-    e#           Multiply Q by that term and subtract from tail.
        }*;          e#         Discard the array of Q,( zeroes.
      ]
    }/
  }j
}

Maxima, 91 bytes
Using the formula:
\$ \Phi_n(x)=\dfrac{x^{n}-1}{\prod\limits_{\stackrel{d|n}{{}_{d<n}}}\Phi_{d}(x)} \$.

Golfed version. Try it online!
f(n):=block(local(p,d),p:x^n-1,for d:1 thru n-1 do(if mod(n,d)=0 then p:p/f(d)),return(p))$

Ungolfed version. Try it online!
f(n) := block(
    local(p, d),
    p : x^n - 1,
    for d:1 thru n-1 do (
        if mod(n, d) = 0 then (
            p : p / f(d)
        )
    ),
    return(p)
)$

for n:1 thru 100 do (
    print(n, " -> ", ratsimp(f(n)))
)$

JavaScript(ES6), 337 333 284 ... 252 250 245 242 bytes
(v,z=[e=[1,u=0]],g=(x,y)=>y?g(y,x%y):x,h=Math,m=(l,x,p=h.cos(l),q=h.sin(l),i=0)=>x.map(()=>[(i&&(n=x[i-1])[0])-(w=x[i])[0]*p+w[1]*q,(i++&&n[1])-w[1]*p-w[0]*q]))=>{for(;++u<v;z=g(v,u)-1?z:[...m(h.PI*2*u/v,z),e]);return z.map(r=>h.round(r[0]))}

Explanation (Selected):
z=[e=[1,u=0]]

Initialize z=(1+0i) * x^0
g=(x,y)=>y?g(y,x%y):x

GCD calculation.
h=Math

Since I need to use Math functions quite a lot, I used another variable here.
m=(l,x,p=h.cos(l),q=h.sin(l),i=-1)=>blah blah blah

Polynomial multiplication.
for(;++u<v;z=g(v,u)-1?z:[...m(h.PI*2*u/v,z),e]);

The formula used is

return z.map(r=>h.round(r[0]))

Compress the output back to an integer array.
Outputs:
An array of integers, with the element at position i representing the coefficient of x^i.
One of the problem JS have is that since JS does not provide native library for calculations on polynomials and complex numbers, they needed to be implemented in an array-like way.
console.log(phi(105)) gives
Array(49)
 0:  1    1:  1    2:  1    3: -0    4: -0    5: -1    6: -1
 7: -2    8: -1    9: -1   10:  0   11: -0   12:  1   13:  1
14:  1   15:  1   16:  1   17:  1   18:  0   19: -0   20: -1
21:  0   22: -1   23: -0   24: -1   25:  0   26: -1   27: -0
28: -1   29:  0   30:  0   31:  1   32:  1   33:  1   34:  1
35:  1   36:  1   37: -0   38: -0   39: -1   40: -1   41: -2
42: -1   43: -1   44: -0   45: -0   46:  1   47:  1   48:  1
length: 49
__proto__: Array(0)

337>333(-4): Changed the code for checking undefined value
333>284(-49): Changed the polynomial multiplication function because it can be simplified
284>277(-7): Deleted some redundant code
277>265(-12): Use 2 variables instead of a 2-element array to drop some bytes in array usage
265>264(-1): Use Array.push() instead of Array.concat() to reduce 4 bytes, but added 3 for the for-loop braces and the z variable
264>263(-1): Further golfed on the last amendment
263>262(-1): Golfed on the for loop
262>260(-2): Golfed out the if clause
260>258(-2): Further combined the declarations
258>252(-6): Golfed on reuse of array references
252>250(-2): Replace some unary operators as binary operators
250>245(-5): Move the increment in Array.map() to the last reference of counter to remove bytes
245>242(-3): Use spread syntax instead of Array.push()

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

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


text:
Build a checkerboard
For this challenge you will print the coordinates and color of each piece at the start of a game of checkers.
Enter the x and y (comma seperated) for every square (indexed 0-7) on a checkerboard, followed by a "r" or "b" (for red or black) where the top of the board (closer to y=0) is red and the bottom is black. newlines between pieces are required and no spaces are necessary.
This is code-golf so answers are scored in bytes with fewer bytes being better.
Trailing newlines are allowed but not necessary and the order must be exactly of that below.
Desired output:
0,0r
0,2r
0,4r
0,6r
1,1r
1,3r
1,5r
1,7r
2,0r
2,2r
2,4r
2,6r
5,1b
5,3b
5,5b
5,7b
6,0b
6,2b
6,4b
6,6b
7,1b
7,3b
7,5b
7,7b

Ok is the above edit sufficient? Sorry this is my first post to this stack exchange. If it's not sufficient could you edit it? Thank you

Is a trailing newline allowed/necessary?

Allowed: yes. Necessary: no

Is there a particular reason you skip x=3 and x=4?

@HyperNeutrino because a checkerboard has only the top and bottom 3 rows filled (at the start of the game)

Oh you're talking about pieces ._. nvm my answer isn't adjustable rip

So that's basically the starting position of Checkers, aka English Draughts. Is that correct?

Does the order of the output matter?

Welcome to PPCG.SE!  A feature of this site that some of us like to use is the sandbox.  You don't have to use it, but it is a useful channel through which to get feedback about any new challenge ideas you have, without having to go through the whole downvote/closevote misery.

@DigitalTrauma Yes order must be as displayed in the question

Can the coordinates be separated by a delimiter other than a new-line? I.e. 0,0r;0,2r;0,4r;0,6r;1,1r;1,3r;1,5r;1,7r;2,0r;2,2r;2,4r;2,6r;5,1b;5,3b;5,5b;5,7b;6,0b;6,2b;6,4b;6,6b;7,1b;7,3b;7,5b;7,7b?

Can the delimiter for the coordinates themselves be different, like a space.
I.e 0 0r\n0 2r\n...?

05AB1E, 26 bytes
2ÝD5+«v4Fy',N·yÉ+„bry3‹èJ,

Try it online!
Explanation
2Ý                           # push [0,1,2]
  D5+                        # duplicate and add 5: [5,6,7]
     «                       # concatenate
      v                      # for each y in [0,1,2,5,6,7] do:
       4F                    # for each N in [0 ... 3] do:
         y                   # push y
          ',                 # push ","
            N·yÉ+            # push N*2+isOdd(y)
                 „br         # push "br"
                    y3‹è     # index into the string with y<3
                        J,   # join everything to a string and print

I feel like [0,1,2,5,6,7] could be pushed in less bytes... but all I could think of was 7Ý34SK so I guess not.

C (gcc), 83 81 79 78 bytes

Saved two bytes thanks to Tahg; golfing x/4+2*(x/12) to x/4+x/12*2.
Saved two bytes thanks to Kevin Cruijssen; golfing x%8*2%8 to x*2%8.
Saved a byte thanks to ceilingcat.

x;main(){for(;x<24;)printf("%d,%d%c\n",x/4+x++/12*2,x*2%8+x/4%2,114-x/12*16);}

Try it online!

You can do x/4+x/12*2 and get rid of the ()

x%8*2%8 can be x*2%8

@ceilingcat Thank you.

JavaScript (ES6), 66 bytes
Includes a trailing newline.
f=(n=24)=>n--?f(n)+[2*(x=n>11)+(y=n>>2),n%4*2+y%2+'rb'[+x]]+`
`:''

Demo

f=(n=24)=>n--?f(n)+[2*(x=n>11)+(y=n>>2),n%4*2+y%2+'rb'[+x]]+`
`:''

console.log(f())

Perl 5, 53 bytes
//&map{say"$',",$_+$'%2,$'<4?r:b}0,2,4,6for 0..2,5..7

Try it online!

Python 2, 74 73 67 bytes
for i in 0,1,2,5,6,7:j=i%2;exec"print`i`+','+`j`+'rb'[i>4];j+=2;"*4

Try it online!

in(...): -> in ...:.

APL (Dyalog Classic), 38 bytes
(⍕⍪4/3 4~⍨⍳8),',',(⍕⍪24⍴⍋8⍴⍳2),12/'rb'

Try it online!

Java 8, 102 96 95 93 91 bytes
v->{for(int i=0;i<24;System.out.printf("%d,%d%c%n",i/4+i/12*2,i*2%8+i/4%2,i++<12?114:98));}

Port from @JonathanFrech's C answer, after which I golfed 5 bytes myself.
Try it here.
Explanation:
v->{                    // Method without empty unused parameter and no return-type
  for(int i=0;i<24;     //  Loop from 0 to 24 (exclusive)
    System.out.printf("%d,%d%c%n",
                        //   Print with format:
                        //   (%d=digit; %c=character; %n=new-line)
      i/4+i/12*2,       //    Print first coordinate
      i*2%8+i/4%2,      //    Print second coordinate
      i++<12?114:98)    //    Print either 'r' or 'b'
  );                    //  End of loop
}                       // End of method

Bash, 59 bytes
Not the shortest, but a fun one:
printf %s\\n {{0,2,6}\,{0,2,4,6}r,{1,5,7}\,{1,3,5,7}b}|sort

Try it online!

Jelly, 35 bytes
8Ḷḟ3ḟ4µḂr7m2ṭ€µ€Ẏµḣ1<3Ḣị⁾rbṭj”,$µ€Y

Try it online!
Full program taking no arguments
Explanation
8Ḷḟ3ḟ4µḂr7m2ṭ€µ€Ẏµḣ1<3Ḣị⁾rbṭj”,$µ€Y  Main link; no arguments
8                                    8
 Ḷ                                   Push 0 .. 8 - 1
  ḟ                                  Remove all instances of
   3                                 3
    ḟ                                Remove all instances of
     4                               4
                €                    For each in [0, 1, 2, 5, 6, 7]
       µḂr7m2ṭ€µ                     Generate all of the piece coordinates across that row
        Ḃ                            row number % 2
         r                           inclusive range up to
          7                          7
           m                         modular; take every   elements
            2                                            2
              €                      For each column coordinate
             ṭ                       Tack the row coordinate (reverse append)
                 Ẏ                   Tighten; flatten once
                                 €   For each piece coordinate (in the right order now)
                 µḣ1<3Ḣị⁾rbṭj”,$µ    Convert to its final output
                  ḣ                  Head; take the first   element(s)
                   1                                      1
                    <                Less Than; compare each element to
                     3               3
                      Ḣ              Head; take the comparison out of the list
                       ị             Index (1-indexed) into
                        ⁾rb          "rb"
                           ṭ         Tack the color character behind
                            j”,$     The coordinates joined by a comma
                            j        Join with separator
                             ”,      ","
                                  Y  Separate by newlines

Java 8, 97 bytes
o->{int i=0,g;for(;i<8;i+=i==2?3:1)for(g=i%2;g<8;g+=2)System.out.println(i+","+g+(i<5?"r":"b"));}

APL (Dyalog), 45 44 bytes*
-1 thanks to ngn.
Niladic function which assumes 0-based indexing (⎕IO←0) which is default on many systems. Prints to STDOUT.
↑' '⎕R','⊃,/(8 ¯8↑¨⊂⍕¨⍸∘.=⍨2|⍳8),¨¨'rb'

Try it online!
(…),¨¨'rb' append "r" to each of the first group of items and "b" to each of the second:
 ⍳8 zero through eight
 2| division remainder when halved
 ∘.+⍨ plus table with itself on along both axes
 ⍸ indices of true values
 ⍕¨ format each (converts to strings with the pattern d d where each d is a digit)
 ⊂ enclose (so we can reuse it for each…)
 8 ¯8↑¨ take the first nine and the last nine
now we have two lists of d d strings
,/ catenation reduction (combine the two lists)
⊃ disclose (because the reduction reduced the rank from 1 to 0)
' '⎕R',' PCRE Replace spaces with commas
↑ mix (the all the lists into a single matrix)

* In Dyalog Classic, counting ⍸ as ⎕U2378.

~2|∘.+⍨⍳8 could be ∘.=⍨2|⍳8

you shouldn't output rows x=3 and x=4

@ngn 2⍴⊂'Thanks'

JavaScript (ES6), 64 bytes
This seems sufficiently different from @Arnauld's to warrant posting:
f=(n=0,y=n>>3,c=y>2)=>y<6?[y+c*2,n%8+y%2+'rb'[+c]]+`
`+f(n+2):''

Explanation:
f=(n = 0,            //the numbered square on checkerboard
   y = n >> 3,       //current row (n / 8 rounded)
   c = y > 2         //false if red pieces, true if black
  ) =>
  y < 6 ?            //if y less than 6
    [                //  using an array automatically adds the comma
     y + c * 2,      //  0 - 2 if red pieces, 5 - 7 if black
     n%8 + y%2 +     //  n%8 returns 0, 2, 4, or 6.
                     //  y%2 returns 0 or 1.
                     //  added, they return the appropriate position (0 - 7)
     'rb'[+c]        //  'r' if red, 'b' if black.  Plus sign coerces boolean to number.
    ]+`              //  new line
    `+
    f(n+2) :         //  recurse on n+2
    ''               //else return an empty string

Snippet:

f=(n=0,y=n>>3,c=y>2)=>y<6?[y+c*2,n%8+y%2+'rb'[+c]]+`
`+f(n+2):''

console.log(f());

Python 2, 63 bytes
x=0;exec"print`x/8+x/24*2`+','+`x%8+x/8%2`+'rb'[x/24];x+=2;"*24

Try it online!

Bubblegum, 59 bytes
00000000: 15ca b101 0030 0400 c1de 2c0a 2462 1f23  .....0....,.$b.#
00000010: d8bf 886f ae3a 531b 310d b8f0 465c 1d0e  ...o.:S.1...F\..
00000020: 24d4 48ec 5b02 2eec 4bf5 5e0e 2454 cb53  $.H.[...K.^.$T.S
00000030: 8380 0baf a5d4 e140 42f5 07              .......@B..

Try it online!

This is the hexdump, right?

@StanStrum Yes this is the hexdump of the actual source. By using the hexdump no unprintables get lost. The actual source doesn't add anything to the answer IMO.

Okay, I was just wondering. Thanks

Pyth, 37 36 35 bytes
isaacg wouldn't be proud
V+U3}5 7FG4p++N\,+yG?!%N2Z1?<N5\r\b

Explanation:
V+U3}5 7            For in the array [0, 1, 2, 5, 6, 7] as N
 FG4                 For in the array [0, 1, 2, 3] as G
  p                   Print without newline:
   ++N\,+yG?!%N2Z1     N, (2 * G) + 1 if N is even, else 0
  ?<N5\r\b            Output with newline "r" if N < 5 else "b"

This uses a simple pattern I cut down a bit. As follows:
If the X coord is even, use the even numbers 0, 2, 4, 6. Else, 1, 3, 5, 7 for Y.
If the X coord is less than 5, the color (r or b) is r. Else, it is b.
Try it online!
edit: overnight got +40 rep on 3 different answers w00t

Javascript (89 bytes):
for(x=y=0,r="r";x<7|y<8;console.log(x+","+y+r),y+=2){if(y>7)y=++x%2;if(x==3){x+=2;r="b"}}

Readable:
for(var x = y = 0, red = true; x < 7 || y < 8; y += 2) {
    if(y > 7) { //new row
        x++;
        y = x % 2;
    }
    if(x == 3) { //new color
        x += 2;
        red = false;
    }
    console.log(x + "," + y + (red ? "r" : "b") );
}

Try it online!

Please note that it is discouraged to answer your own challenge just after posting it.

Ok. Should I take it down and possibly post later?

Ok will do. Thanks for the heads up

This might sound stupid but how do I delete a post on mobile?

@Justin You can't delete posts on mobile.  It is an annoyance to many.

Huh that's weird. I wonder why.

You could put Non-competing for the time being

PowerShell, 63 bytes
0..2+5..7|%{$i=$_;0,2,4,6|%{"$i,$($_+$i%2)"+('r','b')[$i-ge5]}}

Try it online!
Loops over 0,1,2,5,6,7 and each iteration sets $i to the current number. Then loops over 0,2,4,6. Each inner loop, we construct a string starting with $i, then concatenated with our inner loop's current number plus whether $i is even or odd (which gets us 0,2,4,6 one time and 1,3,5,7 the other time), then concatenated with either red or black based on whether $i is -greater-than-or-equal to 5. Those strings are all left on the pipeline and the implicit Write-Output at program completion gives us newlines for free.

J, 48 44 40 37 31 bytes
(}:"1":$.|:8$#:162 69),.12#'rb'

Try it online!
How it works
           8$#:162 69    first 2 columns in binary, take 8 of them
         |:              transpose
       $.                format as a sparse array, kind of looks like the goal
     ":                 "to text"
 }:"1                    delete the last column
       ,.12#'rb'         append 12 rs followed by 12 bs as the last column

C# (.NET Core), 96 bytes
()=>{for(int i=0;i<24;)System.Console.Write($"{i/4+i/12*2},{i*2%8+i/4%2}{(i++>11?"b":"r")}\n");}

Try it online!
Essentially just a port to C# of @JonathanFrech's answer. I couldn't come up with any better way of doing the math.

SOGL V0.12, 31 bytes
⁰¹²⁵⁶⁷’{A4∫«Ha2\⌡HaOļ,pƧbra4>Wo

Try it Here!

Jelly, 27 bytes
8Ḷµḟ3,4pµSḂ$Ðḟj€”,ż⁾rbx12¤Y

A full program which prints the required output.
Try it online!
How
8Ḷµḟ3,4p⁸SḂ$Ðḟj€”,ż⁾rbx12¤Y - Link: no arguments
8                           - literal eight
 Ḷ                          - lowered range = [0,1,2,3,4,5,6,7]
  µ                         - new monadic chain
    3,4                     - literal list = [3,4]
   ḟ                        - filter discard = [0,1,2,5,6,7]
        ⁸                   - chain's left argument = [0,1,2,3,4,5,6,7]
       p                    - Cartesian product = [[0,0],[0,1],...,[2,7],[5,0],...,[7,6],[7,7]]
            Ðḟ              - filter discard if:
           $                -   last two links as a monad:
         S                  -     sum
          Ḃ                 -     modulo by 2
                ”,          - literal comma character
              j€            - join €ach pair with a comma = [0,',',0],[0,',',2],...,[2,',',6],[5,',',1],...,[7,',',5],[7,',',7]]
                         ¤  - nilad followed by links as a nilad:
                   ⁾rb      - literal list = ['r','b']
                       12   - literal twelve
                      x     - repeat = ['r','r','r','r','r','r','r','r','r','r','r','r','b','b','b','b','b','b','b','b','b','b','b','b']
                  ż         - zip together = [[[0,',',0],'r'],[[0,',',2],'r'],...,[[2,',',6],'r'],[[5,',',1],'b'],...,[[7,',',5],'b'],[[7,',',7],'b']]
                          Y - join with newlines = [[0,',',0],'r','\n',[0,',',2],'r','\n',...,'\n',[2,',',6],'r','\n',[5,',',1],'b','\n',...,'\n',[7,',',5],'b','\n',[7,',',7],'b']
                            - implicit print (smashes the list of lists and characters
                            -                 together and prints the digits)

Ruby, 63 60 bytes
[*0..11,*20..31].map{|x|puts [x/4,2*x%8+x[2]]*?,+"rb"[x[4]]}

Bitmask magic saves the byte.
Try it online!

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


text:
One More Program and I'm Out!
Given a positive integer nesting level n and string s of printable ascii characters( to ~, output a program which, when run in the same language, outputs a program which outputs a program . . . which outputs the string s.
A total of n programs should be generated, all of which should be run in the same language as your answer.
Note: you may output programs or functions -- anything you are allowed by default as a submission.
You may input s with escaped characters, how a program or function in your language would usually input a string.

Example
For example, given n=1 and s="recursion", a Python 2 program might output:
print "recursion"

Running this would output:
recursion

Given n=2 and s="PPCG", a Python 2 program might output:
print "print \"PPCG\" "

Running this outputs:
print "PPCG"

Running this outputs:
PPCG

Related (+title inspiration): One more LUL and I'm out
Also Related (in sandbox - now deleted, but can still be viewed with enough reputation): Source Code Recursion
Test Cases
Make sure that your code works for the following test cases (one per line):
n s
2 PPCG
4 Robert'); DROP TABLE Students;--
17 Deep
2 Spaces In Here
3 "Don't forget quotes!"
5 'Backt`cks might be a h`tch'
6 5%s
8 [Brackets]<Are>(Great){Usually}
3 !"#$%&'()*+,-./ 0123456789:;<=>?@ABCDEFGHIJKLMN
6 OPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
7 THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG
3 the quick brown fox jumps over the lazy dog

Was reading the challenge and was like "hey, that looks very familiar..", and then noticed your "Also Related (in sandbox): Source Code Inspiration" to my Sandbox question. :) I'll leave my question there for now, but will delete it after a couple of weeks. Yours is basically the same, except with the addition of an integer parameter.

As suggested here, is it allowed to return anonymous functions instead of programs?

Does "positive integer" include 0?

Did you choose program for a reason? The default is function or program? Is it allowed to have a function printing a function?

Can we use escape characters in the input or must submissions handle inputs that are hard (possibly impossible in some languages) to parse?

@Arnauld yes, an anonymous function may be output.

@FelixPalmen No. Positive integer does not include 0, so you will never be asked to output s directly

@StewieGriffin yes, escape characters may be used, such as inputting 'don\'t' in Python.

Then those test cases doesn't make much sense. They seem to suggest the input format is very strict. Why else have all the "Don't forget quotes", "Back ticks might be a hitch", Little bobby tables and so on?

@StewieGriffin because escaping in sub-expressions or nested programs might be problematic (and someone asked for quote test cases in sandbox).

Is there any consensus on meta about that? The fact that a program or function is able to process a string including some special characters and the valid way(s) to pass it such a string properly are two completely independent issues, IMHO. String unescaping usually takes place at the tokenizer level exclusively and the final program is not even aware of that. Now, if a program really needs to receive, say, two raw backslashes instead of one, that would be indeed a problem.

"You may input s with escaped characters, however you would usually input a string." What does this mean?

@Jakob I think your confusion comes from "however" able to be used as a conjunction. Specified in question.

Jelly, 2 bytes
Ṿ¡

Try it online!
Ṿ¡  Main link; left argument (text) is x, right argument (repetitions) is y
 ¡  Repeat y times:
Ṿ   Uneval x; produce code that outputs x

hehe builtins

This is broken, "hi" produces hi, not "hi"

@Tahg Jelly input is automatically evaluated as Python code if it doesn't throw an error. If it does, then it's just a string. You'd have to do '"hi"' to see the expected outcome

JavaScript (ES6), 47 44 bytes
Saved 3 bytes thanks to @HermanLauenstein
Takes input in currying syntax (n)(s).
n=>g=s=>`alert(atob("${btoa(--n?g(s):s)}"))`

Example
f(2)('PPCG')

Will output:
'alert(atob("YWxlcnQoYXRvYigiVUZCRFJ3PT0iKSk="))'

Which will print:
'alert(atob("UFBDRw=="))'

Which will print:
'PPCG'

Demo
A more complex example where alert() has been overridden so that intermediate results are printed to the console and automatically executed.

let f =

n=>g=s=>`alert(atob("${btoa(--n?g(s):s)}"))`

alert = s => { console.log(s); try { eval(s); } catch(e) {} }

alert(f(5)("'Backt`cks might be a h`tch'"));

Alternate version, 40 bytes
Suggested by @Shaggy
This one returns an anonymous function instead of a full program.
n=>g=s=>`_=>atob("${btoa(--n?g(s):s)}")`

Could you return an anonymous function, instead of using the alert? 41 bytes

@Shaggy I don't really know. I've asked the OP.

If not, maybe you could get away with an IIFE instead for 45 bytes.

-3 bytes using currying: n=>g=s=>BTalert(atob("${btoa(--n?g(s):s)}"))BT (replace BT with backticks)

@HermanLauenstein Thanks! :)

The same can be used in the alternate version: n=>g=s=>BT_=>atob("${btoa(--n?g(s):s)}")BT (replace BT with backticks

sh + coreutils, 31 bytes
yes exec sed 1d \$0|sed $1q;cat

Takes n as a command-line parameter and s on STDIN.

This code says: "Yes, you definitely have to execute me."

Can you add an explanation? I’m having trouble working it out

@JoshRagem yes repeatedly prints its command line, which is exec sed 1d $0 (the $ is a shell metacharacter so it has to be quoted). sed $1q stops printing after $1 (i.e. n) lines. cat then copies the input string. The resulting file is a sh script that tells the shell to replace itself with a copy of sed with the parameters 1d and the script's file name. sed then skips the first line of the file and outputs the rest. Each script has one fewer exec sed 1d $0 prefix, until after n executions only the original input is printed.

Python 2, 40 bytes
f=lambda r,t:r and"print%r"%f(r-1,t)or t

Try it online!
-4 bytes thanks to xnor

Haskell, 17 bytes
As of when I write this, this is the shortest answer for a non-golfing-specific language.
It is a function which takes s and n in that order, and returns the result or the source code of an expression which, when evaluated, returns the next source code.
(!!).iterate show

Argument for why this counts:

Solutions are allowed to be functions.
Their outputs are allowed to be functions.
Those functions have no parameters.
In Haskell, since it is lazy and everything-is-curried, the most natural — for practical programming purposes — definition of a 0-parameter function is the same as its result; the closest alternative, a 1-parameter function which ignores the parameter, is silly.

If f is given PPCG and 2 as its parameters, the result is the text "\"PPCG\"" (first generated function), which when evaluated returns the text "PPCG" (second generated funtion), and when that is evaluated it returns PPCG.
Thanks to nimi for suggesting a shortening.

There is a relevant Meta question on the issue of functions with no arguments in Haskell, though it hasn't received that much attention yet and still has open questions: https://codegolf.meta.stackexchange.com/q/12924/56433

APL (Dyalog), 24 23 bytes
-1 thanks to ngn.
This is a full program which prompts for s and then for n and prints to STDOUT.
''''{⍺,⍨⍺,⍵/⍨1+⍵=⍺}⍣⎕⊢⍞

Try it online! (the 17 Deep case is omitted as it exceeds TIO's output limit – works offline)
⍞ prompt for s
⊢ yield that (to separate ⎕ and ⍞)
''''{…}⍣⎕ prompt for n and apply this lambda with a single quote as left argument that many times. ⍺ stands for the left argument (the quote) and ⍵ is stands for the right argument (the input text):
 ⍵=⍺ Boolean where the text is equal to a quote
 1+ add one
 ⍵/⍨ replicate each character of the argument the corresponding number of times
 ⍺, prepend a quote
 ⍺,⍨ append a quote
This works because strings in APL are ' delimited and single-quotes in strings are doubled, while no other characters need escaping.

Dyalog APL also ships with a utility (⎕SE.Dyalog.Utils.repObj) that generates an APL expression which evaluates to its argument (similar to Jelly's uneval). The following program is therefore equivalent to the above, but works for all arrays:
⎕SE.Dyalog.Utils.repObj⍣⎕⊢⎕

Try it online!

I think APLX allows "doubly-" as well as 'singly-quoted' strings. If the rest works there, you can save a byte :) ngn/apl used to but I removed "" recently

Consider passing the quote as ⍺.- that saves (at least) a byte.

@ngn Thanks, but APLX doesn't have dfns. NARS2000 has both double-quotes and and dfns, but characters cost two bytes each.

Java 8, 95 93 bytes
String c(String s,int n){return"v->\""+(n-->1?c(s,n).replaceAll("[\\\\\"]","\\\\$0"):s)+'"';}

-2 bytes thanks to @Lynn.
Escaping special characters is so annoying in Java..
Try it here and try the resulting method here.
Explanation:
String c(String s,int n){  // Method with String and int parameters and String return-type
  return"v->\""+           //  Return literal "v->" + a leading double-quote +
   (n-->1?                 //   If `n` is larger than 1:
     c(s,n)                //    Recursive-call,
      .replaceAll("[\\\\\"]","\\\\$0")
                           //    with all double-quotes ('"') and slashes ('\') escaped
    :                      //   Else:
     s)                    //    The input String
   +'"';                   //   + a trailing double quote
}                          // End of method

Additional explanation for the regex replacement:
.replaceAll("[\\\\\"]","\\\\$0")
.replaceAll("        ","      ")  // Replace the match of the 1st String, with the 2nd
             [      ]             //  One of these inner characters:
              \\\\                //   Escaped slash ('\')
                  \"              //   Escaped double-quote ('"')
                                  //  And replace them with:
                        \\\\      //   Escaped slash ('\'),
                            $0    //   plus found match

Why all these slashes?
\   →  \\       // Escapes a single slash for the regex
\\  →  \\\\     // Escapes both regex-escaped slashes for the String
"   →  \"       // Escapes a double-quote for the String

I don’t think you need to escape " in a regex character class, so \\\\\" (five backslashes) should be fine.

Firefox JavaScript, 41 35 bytes
f=(s,n)=>"_=>"+uneval(--n?f(s,n):s)

Firefox has a nice uneval, which does what it sounds like - unevals a given object, in this case - string.

Underload, 11 bytes
(a(S)*)~^^S

Try it online!
Input needs to start on the stack, with the number on top in the form of a church numeral. I don't know if this is a valid input method, but the specification has no input, and placing input to the top of the stack seems like a stranded method used in such languages.

R, 62 bytes
f=function(n,s){"if"(n,{formals(f)$n=n-1;formals(f)$s=s;f},s)}

Try it online!
Call it like so: f(n,s) followed by n copies of ()
A named function; returns an anonymous function. All it does is modify the default values of the formals of f, allowing the resulting function to be called (and then the result of that called, n times). when n reaches 0, it returns s.
R is actually not too bad at escaping! It uses C-style escaping, so you just have to take the input, replace " with \" and \ with \\, and then wrap the whole thing in " ".

QuadR, 8 bytes
Simple translation of ngn's answer.
Takes n as argument and s as Input.
^|'|$
'&

Try it online!
PCRE Replace all instances of
^|'|$ Beginning of line OR Quote OR End of line
'& with a Quote and the entire match
The Argument specifies how many times to repeat the transformation.

ah, now I know what that language is for :)

GolfScript, 5 bytes
~{`}*

Try it online!

Excel VBA (32-Bit), 67 Bytes
Version Restricted to 32-Bit Excel VBA because 2^i evaluates without error in 32-Bit VBA, but not in 64-Bit VBA
Anonymous VBE immediate window function that takes inputs n and s from from ranges [A1] and [B1] and outputs an anonymous function that when evaluated down to only a terminal (after n iterations) outputs only s as that terminal
For i=0To[A1-1]:q=q+"?"+String(2^i,34):Next:?q[B1]Replace(q,"?","")

Sample Input / Output
[A1:B1]=Array(7, "PPCG")
For i=0To[A1-1]:q=q+"?"+String(2^i,34):Next:?q[B1]Replace(q,"?","")
?"?""?""""?""""""""?""""""""""""""""?""""""""""""""""""""""""""""""""?""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""PPCG"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
?"?""?""""?""""""""?""""""""""""""""?""""""""""""""""""""""""""""""""PPCG"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
?"?""?""""?""""""""?""""""""""""""""PPCG"""""""""""""""""""""""""""""""
?"?""?""""?""""""""PPCG"""""""""""""""
?"?""?""""PPCG"""""""
?"?""PPCG"""
?"PPCG"
PPCG

Vyxal, 2 bytes
(q

Try it Online!
N times, uneval the string.

APL (Dyalog Classic), 19 bytes
'^|''|$'⎕r'''&'⍣⎕⊢⍞

Try it online!

That's very clever. I tried this approach, but didn't think of prepending.

Sell also this.

Pyth, 21 bytes
L++NsXbJ,N\\+L\\JNyFz

Try it here.
Unfortunately the recursive function (not full program as above) is longer (24 bytes):
M?GgtG++NsXHJ,N\\+L\\JNH

Ruby, 34 bytes
%p is a Ruby-specific printf flag that gets the inspect value of its argument, similar to %r in Python. $><< means print.
f=->n,s{"$><<%p"%(n>1?f[n-1,s]:s)}

Try it online!


text:
Simulate Alpha Decay
Alpha Decay is a kind of radiation decay where every time the atom "decays", it loses a helium nucleus (an alpha particle). This means that an atom loses 2 protons and 2 neutrons each time. Your task is to simulate this, including the problems that occur during alpha decay.
Given two integers as input, \$m\$ and \$p\$, where \$1 < p < m\$, count down in steps of 4 and 2 respectively until either \$m\$ or \$p\$ is equal to or less than 1. At this point, you should output the number which has not yet reached 1.
In order to mimic radioactive decay, however, your program should work when up to any 2 characters are removed from your program. These characters are chosen with uniform probability, and (obviously) chosen without replacement. "Up to" means that the number of characters removed can either be 0, 1 or 2, and your program should work when any number of characters between 0, 1 and 2 are removed.
By "work" it means that, your program, modified or not, should perform the task as specified. Programs may error, so long as the correct output is produced.
Input and output formats are liberal, so long as it's covered by the defaults, it's allowed.
The shortest code in bytes (without characters removed) wins!
Test Cases
m, p     => output
100, 20  => 60
101, 100 => 50
45, 2    => 41
2000, 80 => 1840
57, 23   => 13
80, 40   => 0
81, 40   => 1
81, 41   => 1
43, 42   => 20

Didn't downvote, but as far as I can see you are immediatly eliminating all the non-golfing languages, as the syntax would instantly be invalid if characters were to be removed.

@WheatWizard When any two characters are removed, I'll edit that in

I'm confused as to why the second case outputs 50, shouldn't it output 48?  And the 5th case 9 instead of 13?

If those test cases are just errora and I my understanding is correct, this should be a solution.  I need to go to sleep though so I will check back tomorrow.

@WheatWizard The progression goes like this, $m = 1$ when $p = 50$, not 48. Note that the countdown continues "until either $m$ or $p$ is equal to or less than 1"

Oh why is it less than or equal to 1 rather than zero?  That seems quite odd to me.

@WheatWizard Because, when I wrote this question 3 years ago, I went with 1 rather than 0. Not entirely sure why, but if I'd hazard a guess, I'd say because $m$ and $p$ represent mass and proton numbers, they can't reach 0 as all elements have at least $m, p \ge 1$

Unless a programming language has some form of redundancy implemented, this challenge is probably impossible in that language. I can see that someone will create a language for this, which is prohibited by standard loopholes. So this is probably impossible with the program decay constraint.

@Joao-3 There are a lot of existing languages with redundancy implementations. After all, see Wheat Wizard's comment above - the implementation isn't quite correct, but it's very similar

The description of the radiation hardening says and 2 characters are removed.  Does this include newlines?

@JPeroutek Yes, any two characters could be removed

How would this work with answers with multiple files?


text:
Numbers with similar powers
Given an integer p > 1, find the smallest integer q > p such that the list of exponents in the prime factorization of q is the same of that of p, no matter the order or the value of the prime factors.
Examples
The prime factorization of p = 20 is 22 x 51. The smallest integer greater than p with identical exponents in its prime factorization is q = 28 = 22 x 71.
The prime factorization of p = 2500 is 22 x 54. The smallest integer greater than p with identical exponents in its prime factorization is q = 2704 = 24 x 132.
Rules

The input is guaranteed to be an integer greater than 1.
This is code-golf, so the shortest answer in bytes wins.

Test cases
Input | Output
------+-------
2     | 3
20    | 28
103   | 107
256   | 6561
768   | 1280
2500  | 2704
4494  | 4510
46552 | 46584
75600 | 105840

Just for reference, this is A081761 in the OEIS.

Husk, 10 bytes
§ḟ¤≡ȯÖLgp→

Try it online!
Explantion
§ḟ       →     Find the first number starting from the input + 1 such that...
        p        The prime factorisation
       g         with equal elements grouped together
    ȯÖL          and sorted by length of groups
  ¤≡             has the same shape as the above applied to the input.

Mathematica, 61 bytes
(f[x_]:=Sort[Last/@FactorInteger@x];s=#;While[f@++s!=f@#];s)&

Try it online!
-4 bytes from @Misha Lavrov

A more concise way of writing such a While loop is s=#;While[f@++s!=f@#];s.

You can replace f[x_] with f@x_ to save a byte.

Or even go the composition-salad route of defining f=Last/@#&@*FactorInteger/*Sort.

Jelly, 15 14 bytes
1 byte thanks to Erik the Outgolfer.
ÆEḟ0Ṣ
,Ç€Eð2#Ṫ

Try it online!

It took you almost 3 minutes. ;)

-1 byte by using 2#Ṫ instead

Pyth, 15 bytes
fqFmShMrPd8,QTh

Try it here! or Verify all the test cases.
How does this work?
fqFmShMrPd8,QTh   ~ Full program. Q = first input.

f             h   ~ First input where the condition is truthy over [Q+1, Q+2, ...]
           ,QT    ~ The two element list [Q, current value (T)].
   m              ~ Map over ^ with d.
       Pd         ~ The prime factorization of d.
      r  8        ~ Run-Length encode ^.
    hM            ~ Get the first element of each.
 qF               ~ Check if the values are equal.
                  ~ Output implicitly.

Alternatives
Another 15-byter:
LShMrPb8fqyQyTh

And a couple of (longer) alternatives:
fqFmSlM.gkPd,QTh
LSlM.gkPbfqyQyTh
LS/LPb{PbfqyQyTh
f!-FmlM.gkPd,QTh

Python 2, 176 179 171 170 169 bytes

Added three bytes as the question changed from set of exponents to list of exponents; set(f) was changed to sorted(f).
Saved eight bytes thanks to ovs; golfing the if / else block down to multiplication.
Saved a byte; golfed (n!=r) to (n>r).
Saved a byte; golfed while N>1 to while~-N.

N=input();n=-~N
def F(N):
 r,f=0,[]
 while~-N:
	for n in range(2,-~N):
	 if N%n<1:f+=[1]*(n>r);f[-1]+=n==r;r=n;N/=n;break
 return sorted(f)
while F(N)!=F(n):n+=1
print n

Try it online!

Brachylog, 13 bytes
<.;?{ḋḅlᵐ}ᵐ=∧

Try it online!
It's been a long time since I posted an answer…
Explanation
<.               Input < Output
 .;?             The list [Output, Input]
    {    }ᵐ      Map on [Output, Input]:
     ḋ             Prime decomposition
      ḅ            Group into sublists of consecutive equal elements
       lᵐ          Take the length of each sublist
           =∧    The result of the map must be the same for the Output and the Input

Haskell, 107 bytes
import Data.List
import Data.Numbers.Primes
p=sort.map(1<$).group.primeFactors
f x=until((==p x).p)(+1)$x+1

Try it online! Usage example: f 2500 yields 2704.
Thanks to nimi for pointing out a flaw and saving a bunch of bytes.

Without primeFactors build-in (117 bytes)
import Data.List
1%n=[]
x%n|0<-mod x n=n:div x n%n|m<-n+1=x%m
p=sort.map(1<$).group.(%2)
f x=until((==p x).p)(+1)$x+1

Try it online!

Python - 141 bytes
def s(n):
 i=1;d={}
 while n-1:
  i+=1
  if n%i<1:d[i]=d.get(i,0)+1;n/=i;i=1
 return d.values()
a=input()
j=a+1
while s(a)!=s(j):j+=1
print j

Your program seems to output the wrong value for 2500 as an input; 4624 instead of 2704.

while n-1: can be while~-n:.

05AB1E, 15 bytes
XµN‚εÓ0K{}ËNI›&

Try it online!
Explanation
Xµ                # Loop over N in [0 ...] until 1 match is found
  N‚              # pair N with input
    ε    }        # apply to each
     Ó            # list prime exponents
      0K          # remove zeroes
        {         # sort
          Ë       # check that they are equal
              &   # and
           NI›    # that N is greater than the input

Python 3 + Sympy, 118 bytes
from sympy.ntheory import*
f=lambda k:sorted(factorint(k).values())
g=lambda i,k=2:i<k and f(k)==f(i)and k or g(i,k+1)

Try it online!

J, 32 bytes
>:@]^:(1--:&(_&q:/:~@-.0:))^:_>:

Try it online!
Start from input + 1 >: and keep incrementing while the list of prime factors _&q: minus any zeros -.0:, then sorted /:~@, does not match 1--:.

Japt, 20 bytes
Hideous! But I can't think of a better way :\
@[UX]Ëk ü mÊñÃre}aUÄ

Try it

Ruby, 69 bytes
g=->m{m.prime_division.map{_2}.sort}
->n{((n+1)..).find{g[_1]==g[n]}}

Attempt This Online!


text:
Prime Factorial
For the purposes of this question, the prime factorial of a number n is the result of multiplying all prime numbers smaller than n, and then multiplying the result by n.
Your Task:
Write a program or function to find the prime factorial of a number, as outlined above.
Input:
An integer n where n is greater than one, and the prime factorial of n is smaller than the largest integer your language can support.  However, remember this standard loophole.  Reasonable integer limits only.
Output:
The prime factorial of the input.
Test Cases:
4  -> 24
7  -> 210
32 -> 641795684160

Scoring:
This is code-golf, lowest score in bytes wins!

No way we haven't had this challenge before...

@xnor This?

I didn't think of searching for "primorial" when I was dupe-checking.  Sandbox didn't catch it either.

@Gryphon Yeah, it's strange that "prime factorial" doesn't appear on that challenge. I edited it to make it a bit more searchable.

Thanks.  I thought it was weird we hadn't already had something like this, but I couldn't find anything, so I posted in the sandbox, which also didn't find anything.

Would whoever downvoted please tell me why.  I like to know why my posts are being downvoted.

Jelly, 5 bytes
’ÆRP×

Try it online!
How?

’ÆRP×   Full program.

’       Decrement.
 ÆR     Inclusive prime range.
   P    Product.
    ×   Multiply by the input.

The non-built-in would be 7 bytes: ’ÆPÐfP×

Pyth, 10 bytes
*Q*FfP_TSt

I'm pretty sure this can be golfed some more...

*Q*FfP_TSt     Full program, takes input from stdin and outputs to stdout
*Q             Implicitly output $input multiplied by
  *F           The product of
        St(Q)  All numbers less than $input (Q is added automtaically by Pyth)
    fP_T       As long as they are prime

Pretty sure you can omit the Q

Can you replace St with U?

8 bytes: **FfP_TU or *F+fP_TU

MATLAB/Octave, 23 bytes
@(n)prod(primes(n-1))*n

Try it online!

Mobile bug.. >_>