2

I haven't got sufficient knowledge of time complexity, so my question is:

Is there any direct formula to calculate time complexity of an algorithm, example- I have read somewhere that big O of this code is n*log2(n), so can you tell me how they got this expression?

for(i=1;i<=n;i=i*2)

for this loop I am unable to calculate the big O. This loops will make 7 iterations for a value of n=100. How does that help arrive to the given formula?

6
  • 1
    example of code that is O(n^2logn)????? or else how are we to explain.... Commented Jan 30, 2014 at 6:45
  • for(i=0;i<=n;i=i*2)-for this loop i am unable to calculate the big O. Commented Jan 30, 2014 at 7:57
  • This loop is infinite. Commented Jan 30, 2014 at 8:04
  • Oh sorry i made a mistake , actually its for(i=1;i<=n;i=i*2) Commented Jan 30, 2014 at 8:08
  • Isn't it log2(n)?. Because binary search complexity is the same, and index every time divided by 2. And in this case multiplied by 2. Commented Jan 30, 2014 at 8:30

1 Answer 1

3

By itself, this loop will iterate through ceil(log(n)) times. That's log(n) with log base of 2. This is because after ceiling(log(n)) multiplications, i will have reached or passed n, for any n. A quick example:

For n=100:

Iteration:      i:
    1           1
    2           2
    3           4
    4           8
    5           16
    6           32
    7           64
    8           128

So i will be checked on the 8th iteration and you don't go into the loop, as it's not <= 100. It will be nlog2(n) as you suggest if there's another inner loop that fully loops through n times. Then the two times for the two loops get multiplied to get the total time.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.