5

Here is some code for an integer variable n:

while (n > 0)     
    {         
        n = n/10; // Use integer division     
    } 

I am trying to find the worst-case time analysis for this loop. O(n) is new to me and I am having difficulty with it. Wouldn't this just be O(n)?

Johan
  • 74,508
  • 24
  • 191
  • 319
Ken
  • 53
  • 3
  • If the loop works as expected it would be on `O(log_10 n)` on average and in worst case, which is not as bad `O(n)`. Having said that - not sure whether there is some pathological edge case where something goes wrong ... – Paul Delhanty Apr 26 '14 at 07:42
  • 1
    In what case could this scale as O(n)? – azurefrog Apr 26 '14 at 07:47

1 Answers1

4

Actually that algorithm would be O(log(n)). You are dividing by 10 (knocking off a 0 each time through the loop).

Generally an algorithm is O(n) if it scales linearly with the size of n, but for this, if you increase the size of n by a factor of 10, you only have one more iteration, instead of 10x as many iterations through the loop.


As requested here are a couple of sites with a brief primer. A quick google search will turn up many more:

http://rob-bell.net/2009/06/a-beginners-guide-to-big-o-notation/ http://www.daveperrett.com/articles/2010/12/07/comp-sci-101-big-o-notation/

azurefrog
  • 10,785
  • 7
  • 42
  • 56
  • is that log base 2 or log base 10? in math, plain log usually means the latter, but in cs, the former. – ApproachingDarknessFish Apr 26 '14 at 07:39
  • Generally in big O notation you don't care about the base. – azurefrog Apr 26 '14 at 07:40
  • Do you know of anywhere i can read further into "Big O of n" to further my knowledge. I understand the idea behind it, but actually determining what the time case analysis is throws me off. I feel like I may be over thinking it. I am new to java, but I have completed Java 1, Java 2, and this past week finished algorithms. – Ken Apr 26 '14 at 07:43
  • 1
    Since `log_2(x)=log_10(x)*3.3219` it doesn't matter in Big-o notation if its log2 or log10. – Mathias Apr 26 '14 at 07:44
  • @Mathias thank you Mathias First I couldn't realized @ azurefrog comment "Generally in big O notation you don't care about the base". Now clear. – Grijesh Chauhan Apr 27 '14 at 06:46