What is the time complexity of following function fun()? Assume that log(x) returns log value in base 2.
C++
void fun()
{
int i, j;
for (i = 1; i <= n; i++)
for (j = 1; j <= log (i); j++)
cout << "neveropen" ;
}
|
C
void fun()
{
int i, j;
for (i = 1; i <= n; i++)
for (j = 1; j <= log (i); j++)
printf ( "neveropen" );
}
|
Java
static void fun()
{
int i, j;
for (i = 1 ; i <= n; i++)
for (j = 1 ; j <= log(i); j++)
System.out.printf( "neveropen" );
}
|
Python3
import math
def fun():
i = 0
j = 0
for i in range ( 1 , n + 1 ):
for j in range ( 1 ,math.log(i) + 1 ):
print ( "neveropen" )
|
C#
static void fun()
{
int i, j;
for (i = 1; i <= n; i++)
for (j = 1; j <= log(i); j++)
Console.Write( "neveropen" );
}
|
Javascript
const fun()
{
let i, j;
for (i = 1; i <= n; i++)
for (j = 1; j <= Math.log(i); j++)
document.write( "neveropen" );
}
|
Time Complexity of the above function can be written as θ(log 1) + θ(log 2) + θ(log 3) + . . . . + θ(log n) which is θ(log n!)
Order of growth of ‘log n!’ and ‘n log n’ is same for large values of n, i.e., θ(log n!) = θ(n log n). So time complexity of fun() is θ(n log n).
The expression θ(log n!) = θ(n log n) can be easily derived from following Stirling’s approximation (or Stirling’s formula).
log n! = n*log n - n = O(n*log(n))
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Sources:
http://en.wikipedia.org/wiki/Stirling%27s_approximation
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!