0
function(n): 
{
 for (i = 1; i <= n; i++)
 {
 for (j = 1; j <= n / 2; j++)
 output("")
 }
}

Now I have calculated the time complexity for the first for loop which is O(n). Now the second for loop shows j <= n / 2 so any given n I put, for example, a range of [1,2,...,10] will give me O(log(n)) since it will continuously give me a series of n,n/2,n/4,n/8 .... K.

So if we wanted to compare the relationship it must look something like this 2^n = k.

My question is will it give me O(log(n))?

chqrlie
149k12 gold badges140 silver badges221 bronze badges
asked Sep 20, 2020 at 8:31

2 Answers 2

3

The correct summation according to the code is:

1

So, it's not O(log n). It's O(n^2).

answered Sep 22, 2020 at 4:58
2

No, it does not give you o(logn).
The first for loop is O(n). The second loop is O(n) as well, as the number of iterations grows as a function of n (the growth rate is linear).
It would be the same even by changing the second loop to something like

for (j=1; j<=n/2000; j++)

or in general if you replace the denominator with any constant k.
To conclude, the time compexity is quadratic, i.e., O(n^2)

answered Sep 20, 2020 at 9:07

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.