edited by
6,407 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

0 votes
0 votes
0 answers
2
0 votes
0 votes
1 answer
3
NeelParekh asked Jul 27, 2023
282 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?
2 votes
2 votes
1 answer
4
h4kr asked Dec 30, 2022
477 views
What is the correct time complexity in $\theta()$ ?