5

I have this problem where in class my professor said that the below statement is O(log(n)) where I thought it was O(n). Could someone please clarify how it is O(log(n))?

Printing a number of magnitude n in binary. Assume that printing each bit requires constant time.

8
  • 1
    How many bits does the number n have when written in binary notation? It might help to do some examples for small numbers. Commented Feb 14, 2017 at 0:47
  • this is the question and there is no other information given Commented Feb 14, 2017 at 0:49
  • 2
    So work out some examples. Write the numbers from 0 to 64 in binary. Compare the number itself to the number of bits. Commented Feb 14, 2017 at 0:51
  • 1
    Note that every algorithm which is O(log(n)) is also O(n). So it is correct to say that there is a O(n) solution to this problem. We can even say that the optimal solution is O(n). However, we will usually say this algorithm is O(log(n)) because that is a closer measure of the runtime complexity. As I have suggested in my earlier comments, you should work out some examples to get a better understanding of this analysis. Commented Feb 14, 2017 at 0:55
  • Here's a hint; the logarithm of a number tells about how many digits the number has in the logarithm's base. So, if you have a base-2 logarithm, that tells about how many digits the number has in binary. Commented Feb 14, 2017 at 0:58

3 Answers 3

3

You should work out some examples. Write some numbers in binary. For example, how many bits are there in 63, 255, and 511? Notice that the number of bits does not grow nearly as quickly as the number itself.

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

Comments

3

It's O(log(n)) because you have to divide by 2 every time you are going to print a 0 or 1. For example, to print 256 in binary, you'd have to divide by 2 starting from 256 and print the result of % 2 every time.

256 % 2 -> 0 64% 2 -> 0 32 % 2 -> 0 16 % 2 -> 0 8 % 2 -> 0 4 % 2 -> 0 2 % 2 -> 0 1 % 2 -> 1 

So, for a number of magnitude 256 you would have to iterate 8 times which is equals to log 256.

2 Comments

for example, if i were to do 7 in binary it would be 7%2 = 1 then divide 7 by 2 and it would be 3.5 but as an integer its 3` 3%2 = 1 1%2 = 1 Therefore 7 in binary is 0111, is that correct?
You are correct, it took 3 steps to print each bit. So, that's roughly log 7.
0

O(log(n)) is all about cutting data by half. When each step of an algorithm rules out a fraction of the remaining input -- e.g. you always cut the space in half, or by a third, or even to 99/100 of the previous step -- that algorithm runs in O(log(n)) time.

hope this helps

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.