What will be the order of complexity with respect to time of the following function ?

int func(int n)

{int count = 0;

for (int i = n, i > 0; i/= 2)

for (int j = 0; j<i; j++)

count + = 1;

return count;

}

This question was previously asked in
NIELIT Scientific Assistant IT 5 Dec 2021 Official Paper
View all NIELIT Scientific Assistant Papers >
  1. O(n2)
  2. O(nlogn)
  3. O(n)
  4. O(nlogn)

Answer (Detailed Solution Below)

Option 3 : O(n)
Free
NIELIT Scientific Assistant Quantitative Aptitude Mock Test
0.9 K Users
20 Questions 20 Marks 30 Mins

Detailed Solution

Download Solution PDF

The correct answer is: option 3: O(n)

Concept:

Let’s analyze the time complexity of the given function step-by-step:


int func(int n) {
    int count = 0;
    for (int i = n; i > 0; i /= 2)           / Outer loop: runs log₂n times
        for (int j = 0; j < i; j++)          / Inner loop: runs i times each iteration
            count += 1;
    return count;
}

Outer Loop: i = n; i > 0; i /= 2

  • This loop runs ⌊log₂(n)⌋ + 1 times because i is halved in each iteration.

Inner Loop: for (int j = 0; j < i; j++)

  • In the first iteration, i = n → inner runs n times
  • Next, i = n/2 → inner runs n/2 times
  • Then n/4, n/8, ..., up to 1

Total work done =

\( n + n/2 + n/4 + n/8 + \dots \approx 2n \)

Hence, the overall time complexity is O(n).

Explanation of options:

  • Option 1 – O(n²): ❌ Too large, not accurate.
  • Option 2 – O(nlogn): ❌ Common but incorrect here.
  • Option 3 – O(n):Correct, as explained.
  • Option 4 – O(nlogn): ❌ Repetition of option 2, still incorrect.

Hence, the correct answer is: option 3: O(n)

Latest NIELIT Scientific Assistant Updates

Last updated on Jul 3, 2025

-> NIELIT Scientific Assistant answer key 2025 has been released at the official website. 

-> NIELIT Scientific Assistant admit card 2025 has been released. 

-> NIELIT Scientific Assistant city intimation slip 2025 has been released at the official website.

-> NIELIT Scientific Assistant exam 2025 is scheduled to be conducted on June 28. 

-> A total number of 113 revised vacancies have been announced for the post of Scientific Assistant in Computer Science (CS), Information Technology (IT), and Electronics & Communication (EC) streams.

-> Online application form, last date has been extended up to from 17th April 2025.

->The NIELT has revised the Essential Qualifications for the post of Scientific Assistant. Candidates must possess (M.Sc.)/ (MS)/ (MCA) / (B.E.)/ (B.Tech) in relevant disciplines.

 

-> The NIELIT Scientific Assistant 2025 Notification has been released by the National Institute of Electronics and Information Technology (NIELIT).

Get Free Access Now
Hot Links: teen patti joy mod apk teen patti online teen patti yas teen patti casino apk