Why does Iterator::fold sometimes optimize to a closed-form formula, but a plain for-loop doesn't?

If instead of an inclusive range 1..=n you use an half-open range 1..(n+1), then also the for-loop version gets optimized with the closed-form formula. See example on Compiler Explorer.

In general, inclusive ranges tend to produce less optimized code.

See also this older but still relevant thread: Performance difference among Range, RangeInclusive and reversed