<< #1. Given the following code, why is the time complexity O(n) ??
sum = 0;
for (k = 1; k<=n; k*=2)
for (j =1; j <=k; j++)
sum++;
say n is 32
then the k loop runs 5 times which is logn, for n = 1 , 2 , 4, 8 , 16, 32 , the second loop then runs the sum of all those N's so for n=64 then it runs the amount of times 1+2+4+8+16+32+64 = 127 . so basically its 2n-1.
that would be sooo the bottom loop runs the sum of all the N's in the k for loop. that is what 63. O(2n-1) for that reason i hafve no idea why the answer is O(n) but i suppose 2n-1 is a linear problem and not exponential so its O(n) . i think anyways.
#2. Given the following code, why is the time complexity O(n^2) ??
/* delta and x are float, not int */
x = n;
delta = 1/n;
while (x>0)
x = x-delta; >>
in this one x doesnt decrease as much relatively as n get larger. so its defniitely slower running and not linear like the ohter one. it grows a whole lot in time length as n is increased. from that alone you can cancel out o(logn) or o(n) as its growth functions.
it alwyas takes x/(1/n) times to finish the loop. that is x/(1/n) and since x=n that is n/(1/n) which is n^2.