Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Big O notation and not understading from class lecture

Tags:

java

big-o

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.

like image 327
Kayracer Avatar asked Feb 14 '17 00:02

Kayracer


2 Answers

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.

like image 169
Code-Apprentice Avatar answered Sep 29 '22 04:09

Code-Apprentice


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.

like image 40
alayor Avatar answered Sep 29 '22 02:09

alayor