Good morning and thank you for an interesting discussion.
Thomas, nice work on the formula!! From a different approach, I arrived at a surprisingly similar routine (perhaps the exact same formula but factored differently?) that saves two steps (5 bytes) in RPL and 2 bytes in RPN by reusing the intermediate value \( \begin{align} 3n \mod 4 \end{align} \) .
Originally, I spent some time trying to implement a different formula, which still might be possible,
\(
\begin{align}
a(n) = 6 \lfloor{\frac n 4}\rfloor + \frac{7(n \mod 4) - (n \mod 4)^2}{2}
\end{align}
\)
but arrived a something very similar to Thomas' elegant formula from last week:
\(
\begin{align}
a(n) = \frac{3n + 4(3n \mod 4) - (3n \mod 4)^2}{2}
\end{align}
\)
The formula looks uglier, but is slightly more efficient to calculate with only 6 mathematical operations and 2 less commands in RPL.
Code:
<< 3 * DUP 4 MOD DUP 4 - * - 2 / >>
(40 bytes, checksum #913Bh)
Somehow I feel the stack lifts could be optimized here to replicate the DUP function from RPL, but I've gotten rusty during covid.
Code:
00 { 18-Byte Prgm }
01 3
02 ×
03 RCL ST X
04 4
05 MOD
06 RCL ST X
07 4
08 -
09 ×
10 -
11 2
12 ÷
13 .END.
or python
Code:
example=[0, 3, 5, 6, 6, 9, 11, 12, 12, 15, 17, 18, 18, 21, 23, 24, 24, 27, 29, 30, 30, 33, 35, 36, 36, 39, 41, 42, 42, 45, 47, 48, 48, 51, 53,
54, 54, 57, 59, 60, 60, 63, 65, 66, 66, 69, 71, 72, 72, 75, 77, 78, 78, 81, 83, 84, 84, 87, 89, 90, 90, 93, 95, 96, 96, 99]
def f(n):
i=n%4
return (3*n + 4*i - i**2)//2
assert [f(x) for x in range(len(example))]==example