• recategorized by
1,866 views
0 0 votes
Please tell me the 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;
    }

According to me, it is the summation of n+(n/2)+(n/4)+....+1 so it comes out to be (2^n) - 1. Then what's the time complexity?? In the answer its given O(n). Is it correct ??
    Please tell if I am missing some concept.

1 Answer

1 1 vote
Let say N  is power of 2 ,  

For example let say N  = 16 ,

Now according to code ,  

it runs 16 + 8 + 4 + 2 + 1  

Its a Geometric Progression ,  formula for sum of GP is  ( a * ( r^n - 1  ) / ( r - 1 ) )

a = first  term , r = common ratio.

Here a = 1  and r = 2 ,

Now  sum  =   2 ^ n - 1    where n = number of terms.

As number of terms will always log2(N)  because each time  i is divide by 2.

That measn 2 ^  log2(N) - 1 ,    log cancels out .

Left part is N  , Hence overall complexity should ne linear

O(N) is correct answer
Position:
Show:

Related questions

1 1 vote
1 answers 1 answer
2.2k
2.2k views
Rishabh Gupta 2 asked Aug 31, 2017
2,235 views
Consider the following program segment: count = 0;for 1-1 to n{M= floor(n/1);for j-1 to mcount = count + 1;} The order of magnitude of the program segment is$\theta(n...
3 3 votes
1 1 answer
2.1k
2.1k views
Kapil asked Jan 29, 2017
2,120 views
#include <stdio.h int main(void) { for(i=1;i<=n;i*=2) { for(j=0;j<=i;j++) { for(k=0;k<=n;k++) { ..... O(1)....; } } } return 0; }What is the time complexity of given code...
0 0 votes
1 1 answer
1.3k
1.3k views
LavTheRawkstar asked Jan 12, 2017
1,313 views
INSERTION-SORT (A, n) ⊳ A[1 . . n]for (j ← 2 to len(A) ){key ← A[ j];i ← j – 1 ; while (i 0 and A[i] key) { A[i+1] ← A[i...
2 2 votes
1 1 answer
1.5k
1.5k views
Narasimhan asked Nov 7, 2017
1,454 views
// func() is any constant root functionfor (int i = n; i 0; i = func(i)){ // some O(1) expressions or statements}"In this case, i takes values n, n1/k, (n1/k)1/k = n1/...