Algorithms | Analysis of Algorithms | Question 1
What is time complexity of fun()?
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; } |
chevron_right
filter_none
(A) O(n^2)
(B) O(nLogn)
(C) O(n)
(D) O(nLognLogn)
Answer: (C)
Explanation: For a input integer n, the innermost statement of fun() is executed following times.
n + n/2 + n/4 + … 1
So time complexity T(n) can be written as
T(n) = O(n + n/2 + n/4 + … 1) = O(n)
The value of count is also n + n/2 + n/4 + .. + 1
Recommended Posts:
- Algorithms | Analysis of Algorithms (Recurrences) | Question 11
- Algorithms | Analysis of Algorithms (Recurrences) | Question 8
- Algorithms | Analysis of Algorithms (Recurrences) | Question 9
- Algorithms | Analysis of Algorithms (Recurrences) | Question 11
- Algorithms | Analysis of Algorithms (Recurrences) | Question 11
- Algorithms | Analysis of Algorithms (Recurrences) | Question 4
- Algorithms | Analysis of Algorithms (Recurrences) | Question 7
- Algorithms | Analysis of Algorithms (Recurrences) | Question 2
- Algorithms | Analysis of Algorithms (Recurrences) | Question 3
- Algorithms | Analysis of Algorithms (Recurrences) | Question 6
- Algorithms | Analysis of Algorithms (Recurrences) | Question 1
- Algorithms | Analysis of Algorithms | Question 11
- Algorithms | Analysis of Algorithms | Question 4
- Algorithms | Analysis of Algorithms | Question 13
- Algorithms | Analysis of Algorithms | Question 2



