More similar optimizations: https://matklad.github.io/2025/12/09/do-not-optimize-away.ht...
Couldn't the compiler optimise this still? Make two versions of the function, one with constant folding and one without. Then at runtime, check the value of the parameter and call the corresponding version.
The beginning of that article is slightly wrong: the compiler should compute N(N-1)/2 (and does), because the original code adds up all the numbers from 0 to N excluding N. The usual formulation in math includes the upper bound: the sum of integers from 1 to N, including N, is N(N+1)/2, so you have to replace N by (N-1) if you want a formula for the sum where the last number is N-1.