Any concise way to calculate n * (n+1) / 2 and handling overflow at the same time

Viewed 297

I am trying to implement n * (n + 1) / 2 knowing that n is an int <= 2^16 - 1 (this guarantees that n * (n + 1) / 2 <= 2^31 - 1 so there is no overflow).

Then we know that n * (n + 1) / 2 is guaranteed to be non-negative integer. When calculating this value in a program, though, if we do multiplication n *(n + 1) first, we might get into integer overflow problem. My idea is to use a clumsy condition:

int m;
if (n % 2 == 0) {
    m = (n / 2) * (n + 1);
} else {
    m = n * ((n + 1) / 2);
}

Is there any more concise way of doing this?

5 Answers
Related