Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest possible algorithm to sum numbers up to N [closed]

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.

like image 497
dada Avatar asked Apr 12 '10 18:04

dada


2 Answers

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);.

like image 196
IVlad Avatar answered Sep 23 '22 21:09

IVlad


sum = N * (N + 1) / 2
like image 21
florin Avatar answered Sep 21 '22 21:09

florin