Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Complexity for nested loops dividing by 2

Tags:

c

loops

big-o

I am trying to figure out the complexity of a for loop using Big O notation. I have done this before in my other classes, but this one is more rigorous than the others because it is on the actual algorithm. The code is as follows:

for(i=n ; i>1 ; i/=2) //for any size n
{
    for(j = 1; j < i; j++)
    {
      x+=a
    }
}

I have arrived that the first loop is of O(log_2(n)). As for the second loop I am a little lost! Thank you for the help in the analysis.

like image 290
Hassan Bendouj Avatar asked May 25 '13 10:05

Hassan Bendouj


People also ask

What is the time complexity of two nested loops?

Two nested for loops: O(n²)

How do you calculate time complexity of a nested loop?

As the nested loops always run to completion and there is a constant amount of code within the inner loop, the time complexity can be determined by taking the sum of the number of inner loop iterations in the worst case.

Is a nested loops always O n 2?

"Are nested for-loops always O(n^2)?" To your other question, the answer is no. They aren't always O(n^2) . You can easily create a situation where one of the loops affects the iterations of the other, yielding a different complexity.

How can we reduce the time complexity of two nested loops?

Putting all together. Continuing on the challenge to reduce the iterations on our algorithm, we have to perform the following steps: build the "index" with the information to be accessed later. iterate over the loop and fetch the additional information from the previously created "index"


2 Answers

To formally solve the your algorithm's time complexity, you may use the following steps with Sigma notation:

enter image description here

Also, take a look a the last slide of this very interesting document by Dr. Jauhar.

like image 60
Mohamed Ennahdi El Idrissi Avatar answered Oct 22 '22 15:10

Mohamed Ennahdi El Idrissi


The overall number of iterations of inner loop is n + n/2 + n/4 + ... + 1 which is approximately 2n. So the complexity is O(n).

like image 3
nullptr Avatar answered Oct 22 '22 15:10

nullptr