0

How to analyze the running time of foo function with asymptotic notations?

I thought like that : i=0 is constant time, n%2==0 is constant time, n=n/2 is constant time, i++ is constant time.But I can't say that "while loop run n times".Becasue of n=n/2 expression.

I don't know repeat number of this while loop.For example , if n is 5 ,while loop don't run, if b is 4 , while loop will run 2 times. if b is 14 , while loop will still run 2 times.

 foo(n):
 i=0
 while(n%2==0)
 n=n/2
 i++
 return i
asked Mar 15, 2018 at 17:22
1
  • For any n, n/2 will reach 0 in at most log2(n) steps, so the loop is O(log2(n)) Commented Mar 15, 2018 at 18:13

1 Answer 1

1

It is better to look Best, worst and average case. In your problem, Best case have a constant time O(1), worst case and average case both have O(log(n)) time. Best case is obvious, it is when number if odd. Worst case is obvious too, it happens when your number is like n=2^k. You average is happens if your number is something like n=p*2^k where p is odd. But running time in this case is similar to worst case, because number of loop iterations goes down by dividing your range by 2.

You can analyze this code similar to Binary Search Algorithm. Even though you may find result in first compare, the average case has a O(log(n)) running time.

Regards

answered Mar 15, 2018 at 18:05
3
  • Thanks a lot, also Could you explain that how to find log(n) and why best case is O(n)? I think it should be omega(n) . Commented Mar 15, 2018 at 20:08
  • best case is O(1) not O(n). O(1) means constant time and happens when loop does not run. It means it happens if you pass odd number. Commented Mar 15, 2018 at 20:21
  • Oh, sorry , I misspelled . why not omega(1)? Commented Mar 15, 2018 at 20:28

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.