You are on page 1of 7

void fun()

int i, j;

for (i=1; i<=n; i++)

for (j=1; j<=log(i); j++)

printf("…");

Θ(n log n)

function(int n)

{
if (n==1)

return;

for (int i=1; i<=n; i++)

for (int j=1; j<=n; j++)

printf("*");

break;

Time Complexity of the above function O(n). Even though the inner loop is bounded by n,
but due to break statement it is executing only once.

void function(int n)

int count = 0;

for (int i=n/2; i<=n; i++)

for (int j=1; j<=n; j = 2 * j)

for (int k=1; k<=n; k = k * 2)

count++;

}
Time Complexity of the above function O(n log2n)

void function(int n)

int count = 0;

for (int i=n/2; i<=n; i++)

for (int j=1; j+n/2<=n; j = j++)

for (int k=1; k<=n; k = k * 2)

count++;

Time Complexity of the above function O(n2logn).

void function(int n)

int i = 1, s =1;

while (s <= n)

i++;

s += i;

printf("*");

Time Complexity of the above function O(√n).

void function(int n)

int count = 0;

for (int i=0; i<n; i++)

for (int j=i; j< i*i; j++)

if (j%i == 0)

for (int k=0; k<j; k++)


printf("*");

Solution:Consider the comments in the following function.


void function(int n)

int count = 0;

// executes n times

for (int i=0; i<n; i++)

// executes O(n*n) times.

for (int j=i; j< i*i; j++)

if (j%i == 0)

// executes j times = O(n*n) times

for (int k=0; k<j; k++)

printf("*");

Time Complexity of the above function O(n5).

for (int i = 1; i <=n; i += c) {

for (int j = 1; j <=n; j += c) {

// some O(1) expressions

for (int i = n; i > 0; i += c) {

for (int j = i+1; j <=n; j += c) {

// some O(1) expressions

O(n2)
for (int i = 1; i <=n; i *= c) {

// some O(1) expressions

for (int i = n; i > 0; i /= c) {

// some O(1) expressions

O(Logn)
Recursive Fibonacci is exponential (O(2N)) , not good!

You might also like