edited by
6,488 views
0 votes
0 votes

What is the time complexity of fun()?

int fun(int n)
{
  int count = 0;
   for (int i = 0; i < n; i++)
   for (int j = i; j > 0; j--)
   count = count + 1;
  return count;
} 

 

edited by

2 Answers

0 votes
0 votes
Here count is just a return value  and the complexity depends on two loops mostly on  the loop

there due to j=1 and  j>0 for the first time the loop will executed only 0 times

i =0                  i=1                                            i=2

j=0 times         j will be executed 1 time         j  will be executed 2 times

summing all the  executions of j we will get O(n Square)
0 votes
0 votes

For these questions we will try to find out number of times “count = count + 1;” gets executed.

 

         i   0    1    2  3 ………...   (n-1)
   value of j   0    1    2 values(2,1)

 3

values (3,2,1)

………...

  (n-1)

values (n-1,n-2,….,1)

 value of j indicates the number of times “count = count + 1;” gets executed for each value of i.

So, 0+1+2+3+…...(n-1) times

= $\frac{(n-1)*n}{2}$

=$\frac{(n^{2}-n)}{2}$

 So, time complexity is $O(n^{2})$

And since each execution of j for loop increments count by 1 so value of count = $\frac{(n^{2}-n)}{2}$

Related questions

593
views
1 answers
1 votes
Sajal Mallick asked Nov 28, 2023
593 views
Consider the problem that given a set Sof n integers and another integer x, whether or not there exist two elements in S whose sum is exactly x. What is the worst case ti...
210
views
0 answers
0 votes
308
views
1 answers
0 votes
NeelParekh asked Jul 27, 2023
308 views
If an array is split in the form of increasing and decreasing order then what is TC to find minimum element in the array?
489
views
1 answers
2 votes
h4kr asked Dec 30, 2022
489 views
What is the correct time complexity in $\theta()$ ?