What is time complexity of fun()? ```c int fun(int n) { int count = 0; for…

2024

What is time complexity of fun()? ```c int fun(int n) { int count = 0; for (int i = n; i > 0; i /= 2) for (int j = 0; j < i; j++) count += 1; return count; }

  1. A.

    O(n²)

  2. B.

    O(n*log(n))

  3. C.

    O(n)

  4. D.

    O(n*log (n*log(n)))

Attempted by 92 students.

Show answer & explanation

Correct answer: C

To determine the time complexity of fun(), analyze how many times the inner statement executes. The outer loop starts with i = n and divides i by 2 in each iteration (i = n, n/2, n/4,..., 1). For each value of i, the inner loop runs exactly i times. Therefore, the total number of operations is the sum: n + n/2 + n/4 +... + 1. This forms a geometric series with the first term a = n and common ratio r = 1/2. The sum of this infinite geometric series converges to a * (1 / (1 - r)) = n * 2 = 2n. Since constant factors are ignored in Big-O notation, the total time complexity is O(n). Option A (O(n²)) assumes both loops run n times independently, which is incorrect here. Option B (O(n log n)) would apply if the inner loop ran n times for every outer iteration, but since i decreases exponentially, the total work is linear.

Explore the full course: Tpsc Assistant Technical Officer