4 ms·
It has to. Just imagine what happens when in the iterative algorithm count = count + i is just before overflowing. In that case the O(N) algorithm has no over
by constantcrying 3y ago
It has to. Just imagine what happens when in the iterative algorithm
count = count + i
is just before overflowing.
In that case the O(N) algorithm has no overflow, but if you look at the closed form solution. Surely
(count)*(count-1)
would overflow.
A compiler must never be allowed to swap a non-overflow with a overflow. Which is one big limit of these optimizations.
- valleyer 3y agoSure, but in the scenario you describe, (count-1)*(count-2) also overflows, and that's why the generated code already to 64 bits for the multiply. (See my cousin comment to this one.)