![]() |
VOOZH | about |
Prerequisite: Asymptotic Analysis, Worst, Average and Best Cases, Asymptotic Notations, Analysis of loops.
{ 3T(n-1), if n>0,
T(n) = { 1, otherwise
Solution:
Let us solve using substitution.
T(n) = 3T(n-1)
= 3(3T(n-2))
= 32T(n-2)
= 33T(n-3)
...
...
= 3nT(n-n)
= 3nT(0)
= 3nThis clearly shows that the complexity of this function is O(3n).
{ 2T(n-1) - 1, if n>0,
T(n) = { 1, otherwise
Solution:
Let us try solving this function with substitution.
T(n) = 2T(n-1) - 1
= 2(2T(n-2)-1)-1
= 22(T(n-2)) - 2 - 1
= 22(2T(n-3)-1) - 2 - 1
= 23T(n-3) - 22 - 21 - 20
.....
.....
= 2nT(n-n) - 2n-1 - 2n-2 - 2n-3
..... 22 - 21 - 20= 2n - 2n-1 - 2n-2 - 2n-3
..... 22 - 21 - 20
= 2n - (2n-1)[Note: 2n-1 + 2n-2 + ...... + 20 = 2n - 1]
T(n) = 1
Time Complexity is O(1). Note that while the recurrence relation looks exponential
he solution to the recurrence relation here gives a different result.
Solution: Consider the comments in the following function.
Time Complexity: O(n), Even though the inner loop is bounded by n, but due to the break statement, it is executing only once.
Solution: Consider the comments in the following function.
Time Complexity: O(n log2n).
Solution: Consider the comments in the following function.
Time Complexity: O(n2logn).
Solution: We can define the terms 's' according to relation si = si-1 + i. The value of 'i' increases by one for each iteration. The value contained in 's' at the ith iteration is the sum of the first 'i' positive integers. If k is total number of iterations taken by the program, then while loop terminates if: 1 + 2 + 3 ....+ k = [k(k+1)/2] > n So k = O(√n).
Time Complexity: O(√n).
Solution: Consider the comments in the following function.
Time Complexity: O(n5)
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.