algorithm - Trouble figuring out these tough Big-O examples -
i'm trying study upcoming quiz big-o notation. i've got few examples here they're giving me trouble. seem little advanced lot of basic examples find online help. here problems i'm stuck on.
1. `for (i = 1; <= n/2; = * 2) { sum = sum + product; (j= 1; j < i*i*i; j = j + 2) { sum++; product += sum; } }`
for one, i = * 2
in outer loop implies o(log(n)), , don't think i <= n/2
condition changes because of how ignore constants. outer loop stays o(log(n)). inner loops condition j < i*i*i
confuses me because in terms of 'i' , not 'n'. big-o of inner loop o(i^3)? , big-o entire problem o( (i^3) * log(n) )?
2. `for (i = n; >= 1; = /2) { sum = sum + product (j = 1; j < i*i; j = j + 2) { sum ++; (k = 1 ; k < i*i*j; k++) product *= * j; } }`
for one, outermost loop implies o(log(n)). middle loop implies, again unsure, o(i^2)? , innermost loop implies o(i^2*j)? i've never seen examples before i'm guessing @ point. big-o notation problem o(i^4 * n * j)?
3. `for (i = 1; < n*n; = i*2) { (j = 0; j < i*i; j++) { sum ++; (k = i*j; k > 0; k = k - 2) product *= * j; } }`
the outermost loop 1 has n^2 condition, logarithmic increment, think cancels out regular o(n). middle loop o(i^2), , innermost loop think o(n) , trying trick you. problem big-o notation o(n^2 * i^2)?
4. `int = 1, j = 2; while (i <= n) { sum += 1; = * j; j = j * 2; }` 1 did few iterations better see happening: = 1, j = 2 = 2, j = 4 = 8, j = 8 = 64, j = 16 = 1024, j = 32
so clearly, 'i' grows quickly, , condition met quickly. i'm not sure kind of big-o notation is.
any pointers or hints can give appreciated, guys.
you can't add or j o-notation, must converted n.
for first one:
let k log 2 i.
then inner loop done 2^(k*3)/2=2^(3k-1) times each iteration of outer loop.
k goes 1 log2n. total number of iterations sum of 2^(3k-1) k 1 log 2 n 4/7(n^3-1) according wolfram alpha, o(n^3).
for last one, i=j1*j2*j3*...jk, , jm=2^m
i=2^1*2^2*...2^k=2^(1+2+...k)
so 1+2+3+...+k=log 2 n
(k+1)k/2 = log 2 n
which o(sqrt(log n))
btw, log n^2 not n. question better ask @ computer science here.
Comments
Post a Comment