algorithm - Order Of Growth complicated for loops -
for following code fragment, order of growth in terms of n?
int sum = 0; (int = 1; <= n; = i*2) (int j = 1; j <= n; j = j*2) (int k = 1; k <= i; k++) sum++; i have figured there lgn term, stuck on evaluating part : lgn(1 + 4 + 8 + 16 + ....). last term of sequence be? need last term calculate sum.
you have geometric progression in outer loops, there closed form sum of want take log:
1 + 2 + 4 + ... + 2^n = 2^(n+1) - 1 to precise, sum is
1 + ... + 2^(floor(ld(n)) with ld denoting logarithm base 2.
the outer 2 loops independent each other, while innermost loop depends on i. there single operation (increment) in innermost loop, means number of visits innermost loop equals summation result.
\sum_i=1..( floor(ld(n)) ) { \sum_j=1..( floor(ld(n)) ) { \sum_k=1..2^i { 1 } } } // adjust innermost summation bounds = \sum_i=1..( floor(ld(n)) ) { \sum_j=1..( floor(ld(n)) ) { -1 + \sum_k=0..2^i { 1 } } } // swap outer summations , resolve innermost summation = \sum_j=1..( floor(ld(n)) ) { \sum_i=1..( floor(ld(n)) ) { 2^i } } // resolve inner summation = \sum_j=1..( floor(ld(n)) ) { 2^(floor(ld(n)) + 1) - 2 } // resolve outer summation = ld(n) * n - 2 * floor(ld(n)) this amounts o(n log n) ( second term in expression vanishes asymptotically wrt first ) in big-oh notation.
Comments
Post a Comment