What would be the time complexity of this code? Big O notation

53 Views Asked by At

`

def func5(n, m):
     i = 0
    while i < n:
        j = 1
        while j < m:
            print(i+j)
            j *= 3
        i += 1

`

I have gotten answers O(n*m) and O(n(log(m)). Which is it?

1

There are 1 best solutions below

0
Prabhand Reddy On
n = 1, outer loop runs :  1 time  
n = 2, outer loop runs :  2 times  
n = k, outer loop runs :  k times  
n = n, outer loop runs :  n times

for each iteration of outer loop,

lets assume that inner loop runs for 'k' times which implies the values of 'j' are

j = 1, j = 3, j = 3^2, j = 3^3, j = 3^k-1

after this for next iteration of inner loop the value of 'j' will be greater than or equal to m. so, the loop stops

3^k  >= m  
k >= log(m)  
Here, log(m) with base 3

which implies that inner loop runs for log(m) times

Hence, Time Complexity = O(n*log(m))

here, O(n*log(m)) is least upper bound compared to O(n, m), O(n^2,m) and so on

In general, Big-Oh implies upper bound.

big-Oh

for a function f(n), it is said to be upper bounded by g(n) only if 
f(n) <= cg(n) for c > 0, n > n0, n0 >= 1    
then we can say that f(n) = O(g(n))  

lets assume that g(n) upper bounds f(n) then g(n^2) also upper bounds f(n).  
similarly g(n^3), g(n^4),g(2^n) also upper bounds g(n)   

so, always consider least upper bond or tighter bond for Time complexity