Skip to content

ISRO Scientist/Engineer CSE 2017Algorithms › Time Complexity and Recurrences

ISRO Scientist/Engineer CSE 2017 PYQ: //Consider the program void function(int n) { int i,j,count=0; for(i=n/2;i<=n;i++) for(j=1;j<=n;j=j*2)…

//Consider the program
void function(int n)
{
    int i,j,count=0;
    for(i=n/2;i<=n;i++)
       for(j=1;j<=n;j=j*2)
          count++;
}

The complexity of the program is

  1. A
    $O(\log n)$
  2. B
    $O(n^2)$
  3. C
    $O(n^2 \log n)$
  4. D
    $O(n \log n)$
    Correct answer

Answer

(D) $O(n \log n)$

Approach

Count the number of times the innermost statement (count++) executes. The outer loop runs about n/2 times, and the inner loop runs about log2(n) times. Since the loops are independent, multiply the counts to get the total operations, then express in Big-O notation.

Reviewed by ISRO IQ Editorial Team.