Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time complexity of fun()?

I was going through this question to calculate time complexity.

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;
}

My first impression was O(n log n) but the answer is O(n). Please help me understand why it is O(n).

like image 755
Prateek Joshi Avatar asked Nov 12 '15 16:11

Prateek Joshi


1 Answers

The inner loop does n iterations, then n/2, then n/4, etc. So the total number of inner loop iterations is:

   n + n/2 + n/4 + n/8 + ... + 1  
<= n * (1 + 1/2 + 1/4 + 1/8 + ...) 
 = 2n

(See Geometric series), and therefore is O(n).

like image 130
interjay Avatar answered Sep 19 '22 18:09

interjay