c++ - How many times does this statement in a triply-nested loop execute? -


this problem

for(i=1;i<=n;i++)     for(j=1;j<=i;j++)         for(k=1;k<=j;k++)             x++; 

now, want know statement x++; how many iterate?? want know formula of solution.

you're looking value of following summation:

  sum(i 1 n)       sum (j 1 i)           sum (k 1 j)               1 

working inside out:

  sum(i 1 n)       sum (j 1 i)           sum (k 1 j)               1 = sum(i 1 n)       sum (j 1 i)           j  = sum(i 1 n)       i(i + 1) / 2 

from here, get

sum (i 1 n) i(i + 1) / 2

= (1/2) sum (i 1 n) (i2 + i)

= (1/2) (sum (i 1 n)i2 + sum (i 1 n) i)

= (1/2) (n(n + 1)(2n + 1) / 6 + n(n + 1) / 2)

you can try simplify polynomial clean, exact value. if need asymptotic upper bound, it's θ(n3).

according wolfram alpha, is

n3 / 6 + n2 / 2 + n / 3

hope helps!


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -