For a given input N, how many times does the enclosed statement executes?
for i in 1 … N loop
for j in 1 … i loop
for k in 1 … j loop
sum = sum + i ;
end loop;
end loop;
end loop;
Can anyone figure out an easy way or a formula to do this in general. Please explain.
C
code to generate sum:N=1 to N=10
:$ gcc sum.c
$ ./a.out
Then, Tried to explore
How this works?
with some diagrams:For,
N=1
:That is (1) = 1
For,
N=2
:That is (1) + (1 + 2) = 4
For,
N=3
:That is (1) + (1 + 2) + ( 1 + 2 + 3 ) = 10
Finally, I could understood that sum of
N
in three loop is:(1) + (sum 0f 1 to 2) + ... + (sum of 1 to (N-2)) + (sum of 1 to (N-1) ) + (sum of 1 to N)
or we can write it as:
=> (1) + (1 + 2) + ...+ (1 + 2 +....+ i) + ... + (1 + 2 + ....+ N-1) + (1 + 2 + ....+ N)
=> ( N * 1 ) + ( (N-1) * 2) + ( (N-2) * 3) +...+ ( (N -i+1) * i ) +... + ( 1 * N)
You can refer here for simplification calculations: (I asked HERE )
[YOUR ANSWER]
= ( ((N) * (N+1) * (N+2)) / 6 )
And, I think its correct. I checked as follows:
Also, The complexity of this algorithm is O(n3)
EDIT:
The following loop also has same numbers of count, that is
= ( ((N) * (N+1) * (N+2)) / 6 )