• edited by
7,918 views
0 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;
} 

 

2 Answers

0 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 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}$

Position:
Show:

Related questions

3 3 votes
1 1 answer
232
232 views
GO Classes asked Aug 31
232 views
The algorithm $\text{ALGSORT}$ sorts an array of distinct integers using comparisons.The function $\text{MININDEX(V,i,j)}$ returns the position of the smallest element in...
1 1 vote
1 1 answer
163
163 views
GO Classes asked Aug 29
163 views
Suppose Huffman coding is implemented as follows.Initially, the $n$ symbols are stored in a min priority queue according to their frequencies.The algorithm repeatedly per...
1 1 vote
1 1 answer
138
138 views
GO Classes asked Aug 26
138 views
Consider,f1(N): x = 0 for i = 0 to N - 1: x++ return xand,f2(N, R): x = 0 for i = 0 to N - 1: for j = 1; j <= R; j = j + j: x = x + f1(j) return xWhat is the order of gro...
2 2 votes
1 1 answer
391
391 views
KrishnaVardhan asked Oct 7, 2024
391 views
Even though there are two for loops some times the Time complexity will be the m+n and some times it will be m*n assuming loops run till m and n respectively.How do we di...