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)
Comentarii