Advertisement

Sum of all integers

Started by October 25, 2002 04:20 PM
12 comments, last by Starwind8748 22 years, 3 months ago
50*101=5050

Killer Eagle Software
UINT Total = 0;
for( UINT i=MinValue; i<=MaxValue; i++)
{
Total += i;
}
Advertisement
The sum of all positive integer diverges in O(n2) towards +∞
The sum of all integers is undefined.

Documents [ GDNet | MSDN | STL | OpenGL | Formats | RTFM | Asking Smart Questions ]
C++ Stuff [ MinGW | Loki | SDL | Boost. | STLport | FLTK | ACCU Recommended Books ]


[edited by - Fruny on October 28, 2002 9:12:51 PM]
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
quote:
Original post by Paradigm Shifter
My favourite way of seeing the result is to imagine a "pyramid" of 1x1 squares, the first row has 1, the second 2, all the way up to row n. You rotate the pyramid 180 degrees and it fits nicely together with itself forming a rectangle of area
n( n + 1 )



Here''s another trick to understand why it works (although I wouldn''t call it a proof) :

Here''s the 1 to n ( n > 0) sum :

SUM = 1 + 2 + 3 + ...+n-1+ n

Now let''s see this in reverse order too :

SUM = 1 + 2 + ...+n-1+ n
SUM = n +n-1+ ...+ 2 + 1

Note that each column sum gives you n+1, so if you add them you have :

2*SUM = n+1 + n+1 + n+1 ... + n+1 (n times)
2*SUM = n(n+1)
SUM = (n(n+1))/2

This topic is closed to new replies.

Advertisement