retagged by
1 flag 1,082 views
1 votes
1 votes
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;
}

then this function should give O(nlogn).

since outer loop run O(logn) time

inner loop O(n) time 

  • 🚩 Duplicate | 👮 Hira Thakur | 💬 “https://gateoverflow.in/4543/time-complexity”
retagged by

3 Answers

Best answer
3 votes
3 votes

The correct answer indeed will be $ O(N) $

Here is the explanation, Let consider $ N = 2^K $

then the outer loop will run up to $ (Log N) $ times.

Then total work done by the program can be represented as,

T(n) = $ \sum_{i=0}^{log N} \frac{N}{2^i} $

T(n) = $ \sum_{i=0}^{log N} \frac{2^K}{2^i} $         (We have considered $ N = 2^{K} $ )

T(n) = $ \sum_{i=0}^{log N} 2^{K-i} $ 

T(n) <= $ \sum_{i=0}^{log N} 2^{K} $ 

T(n) <= $ 2^{K+1} $

T(n) <= $ 2^{log N+1} $
 
T(n) = $ O(2N) $.
 
Hence Time complexity of the program is O(N).
 
selected by
0 votes
0 votes
O(n) or o(n)can not  definitely place upper bound  n+n/2+n/4+n/8+ .....1

hence ans can be O(nlogn)
0 votes
0 votes

See here T(n)=n+n/2+n/4+n/6+.............................logn term

                      =n(1+1/2+1/4+1/6+.....................1/2logn-1)

Let n=ak

T(n)=ak(1+1/2+1/4+1/6+..................1/2k-1)       .................(1)

Now solve decreasing GP=1+1/2+1/4+1/6+.....................1/2k-1

Here a=1 , r=1/2

S=a(1-r)n/1-r

  =(1-(1/2)k)/(1-1/2)

  =2(1-1/2k)

Now From Equation (1)....

T(n)=2ak(1-1/2k)

Since n=ak  SO,

T(n)=2n(1-1/2logn)

       =2n(1-1/nlog2)

So T(n)=O(n)

edited by

Related questions

2 votes
2 votes
1 answer
1
0 votes
0 votes
2 answers
2
Mak Indus asked Nov 10, 2018
285 views
Given an array of distinct integers A[1, 2,…n]. Find the tightest upper bound to check the existence of any index i for which A[i]= i.(a) O (1) ...
0 votes
0 votes
1 answer
3
anonymous asked Jun 26, 2016
678 views