K
Keith Thompson
Ben Pfaff said:I once had a teacher deduct points for using "n * (n + 1) / 2" as
the sum of 1...n, because she didn't know that it was a correct
formula. I had to demonstrate to her and the entire class that
it was correct.
Suppose you're using a system where int is 16 bits, and n==255. The
intermediate expression 255*256 yields 65280, which overflows, though
the final result is 32640, which doesn't. The formula invokes
undefined behavior, whereas adding the numbers 1..n individually
wouldn't. Similar examples exist for other sizes of int.
A workaround is to divide either n or n+1, whichever is even, by 2
before doing the multiplication:
n%2==0 ? (n/2) * (n+1) : n * (n+1)/2