I want a really fast algorithm or code in C to do the following task: sum all numbers from 1 to N for any given integer N, without assuming N is positive. I made a loop summing from 1 to N, but it is too slow.
If N
is positive: int sum = N*(N+1)/2;
If N
is negative: int tempN = -N; int sum = 1 + tempN*(tempN+1)/2 * (-1);
.
sum = N * (N + 1) / 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With