See solution below, I would like some constructive feedback.
what is the running time in O(n) below.
int a = 0;
int k = n*n*n; //n^3
while(k > 1)
{
for (int j=0; j<k; j++) //runs from 0->k
{ a--; }
k = k/2; //divides by 2 each iteration
}
each time the for loop runs, it gives a constant x k.
= 0xn^3 + 1x (n^3/2) + 2x(n^3/4) +…+ nx(n^3/2^n)
= n^3 (0 + 1/2 + 2/4 +…+ n/2^n) <- anyone know how I can simplify this down further?
Edit: i am assuming we would use the arithmetic series somehow….
Let’s use k first
in first while loop, the for loop runs k times
in second while loop, the for loop runs k/2 times
in third while loop, the for loop runs k/4 times
…
so in total it runs ( k + k/2 + k/4 + k/8 + … + 1) times
after extract the k, it’s k * ( 1 + 1/2 + 1/4 + 1/8 + … + 1/k)
as k increases, the part in parentheses becomes 2, which we can ignore
change k to n^3, the result is O(n^3)