top of page

Discuss the running time of the following snippet of code: count=0 for (i=l, i<=n, i++) for (j=1, j<=n, j=2*j) count++

The code snippet is:

count=0
for (i=l, i<=n, i++)
	for (j=1, j<=n, j=2*j)
		count++

The outer loop runs from i=1 to i=n. This loop executes exactly n times.


The inner loop initializes j to 1 and doubles j in each iteration, continuing as long as j is less than or equal to n.


The sequence of values for j in the inner loop will be: 1,2,4,8,…,2^k.


We need to find the maximum value of k such that 2^k≤𝑛

2k≤n

Taking logarithm base 2 on both sides

k≤log2​(n)

Therefore, the inner loop runs O(logn) times.


Since the outer loop runs 𝑛n times and the inner loop runs O(logn) times for each iteration of the outer loop, the total running time T(n) can be calculated as:

O(nlogn)

69 views0 comments
logo

Crookshanks Academy is an online learning platform with free netflix styled courses.

Crookshanks Academy 2023 ©️ All Rights Reserved

This content is protected from right clicks.
bottom of page