0

Can you explain to me how you get the Big O notation for the runtime of the following snippet of code?

for x = 1 to n
{
    y = 1
    while y < n
       y = y + y
}

Can you explain the steps on how you get the big O notation for it? Also why doesn't it matter if there a bunch of statements inside a for loop when calculating the big O notation? Wouldn't the number of operations increase as n gets larger if there are more O(1) statements inside the for loop? Help would greatly be appreciated.

Raphael
  • 73,212
  • 30
  • 182
  • 400
Armon Safai
  • 143
  • 7

1 Answers1

2

Hint: First of all, since the code in the loop doesn't depend on $x$, the running time of the code is $\Theta(n)$ times the running time of the code inside the outer loop. Second, the running time of the code in the inner loop is $\Theta(\ell)$, where $\ell$ is the number of iterations of the while loop, which is the number of times you need to double $1$ until you reach or exceed $n$. Perhaps you can find a formula for $\ell$.

Yuval Filmus
  • 280,205
  • 27
  • 317
  • 514