Question
Download Solution PDFWhat 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;
}
Answer (Detailed Solution Below)
Detailed Solution
Download Solution PDFThe 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 runsn
times - Next,
i = n/2
→ inner runsn/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)
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).