Introduction (may be ignored)
Putting all positive numbers in its regular order (1, 2, 3, ...) is a bit boring, isn't it? So here is a series of challenges around permutations (reshuffelings) of all positive numbers. This is the third challenge in this series (links to the first and second challenges).
In this challenge, we will arrange the natural numbers in rows of increasing length in such a way that the sum of each row is a prime. What I find really amazing about this, is that every natural number has a place in this arrangement. No numbers are skipped!
This visualisation of this arrangement looks like this:
row numbers sum
1 1 1
2 2 3 5
3 4 5 8 17
4 6 7 9 15 37
5 10 11 12 13 21 67
6 14 16 17 18 19 23 107
etc.
We can read the elements from the rows in this triangle. The first 20 elements are: 1, 2, 3, 4, 5, 8, 6, 7, 9, 15, 10, 11, 12, 13, 21, 14, 16, 17, 18, 19 (yes, there is a New Order song hidden in this sequence).
Since this is a "pure sequence" challenge, the task is to output \$a(n)\$ for a given \$n\$ as input, where \$a(n)\$ is A162371.
Task
Given an integer input \$n\$, output \$a(n)\$ in integer format.
\$a(n)\$ is defined as the \$n\$th element of the lexicographically earliest permutation of the natural numbers such that, when seen as a triangle read by rows, for n>1 the sums of rows are prime numbers. Since the first lexicographical permutation of natural numbers starts with 1, \$a(1)\$ is 1. Note that by this definition \$a(1) = 1\$ and \$a(1)\$ is not required to be prime. This is OEIS sequence A162371.
Note: 1-based indexing is assumed here; you may use 0-based indexing, so \$a(0) = 1; a(1) = 2\$, etc. Please mention this in your answer if you choose to use this.
Test cases
Input | Output
---------------
1 | 1
5 | 5
20 | 19
50 | 50
78 | 87
123 | 123
1234 | 1233
3000 | 3000
9999 | 9999
29890 | 29913
Rules
- Input and output are integers (your program should at least support input and output in the range of 1 up to 32767)
- Invalid input (0, floats, strings, negative values, etc.) may lead to unpredicted output, errors or (un)defined behaviour.
- Default I/O rules apply.
- Default loopholes are forbidden.
- This is code-golf, so the shortest answers in bytes wins