First we clean up the loop...
Code:
for ( i = 0; i < n; i++ )
{
for( j = 0; j < i; j++ )
sum++;
}
Now we do a test run "on paper"
Code:
for ( i = 0; i < n; i++ )
for( j = 0; j < i; j++ )
n = 2
i = 0
j = 0, sum = 1
i = 1
j = 0, sum = 2
j = 1, sum = 3
Now let's see if we can't do something about that pesky inner loop...
Code:
i = 0
sum += i + 1
(ie: sum = 1)
i = 1
sum += i + 1
(ie: sum = 3)
So you see you can skip the inner loop entirely. Now, I've changed it a bit, because I like counting from 0 instead of 1, because it looks cleaner to me. You could do the same, if you start at 1, and do a <= like you did, removing the "+1" segment.
Code:
for( i = 1; i <= n; i++ )
sum += i;
Should give us...
Code:
i = 1, sum = 1 ( 0 + 1 )
i = 2, sum = 3 ( 1 + 2 )
You can skip the whole loop...
Code:
sum = ((n + 1) * (n / 2))
[edit]
Hm..
Actually you can only sum that way (n+1)*(n/2) if N is even. If it is odd, you have to add a bit.
n is even
( n + 1 ) * ( n / 2 )
n = 2
(1 + 2 = 3) == ( (2+1)*(1) )
n = 4
(1 + 2 + 3 + 4 = 10) == ( (4+1)*(2) )
n is odd
( ( n + 1 ) * ( n / 2 ) ) + ( (n + 1 ) / 2 )
n = 3
( 1 + 2 + 3 = 6) == ( (3+1)*(n/2)+((n+1)/2) ) == ( (4)*(1)+(2) )
n = 5
( 1 + 2 + 3 + 4 + 5 == 15 ) == ( (5+1)*(5/2)+(6/2) ) == ( 6*2+3 )
That looks about right.
Oddly enough...the number of objects, summed 1 to N, equal the number of loop iterations.
[/edit]
Quzah.