0 0 votes closed as a duplicate of: TIME COMPLEXITY What is time complexity of fun()? 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; } (A) O(n^2) (B) O(nLogn) (C) O(n) (D) O(nLognLogn) Algorithms algorithms time-complexity geeksforgeeks-test-series + – Sumit Singh Chauhan 4.6k views comment Share Follow Print See all 8 Comments 8 8 Comments reply Sumit Singh Chauhan commented Aug 18, 2018 reply Follow flag Isn't its answer have to be nlogn. 0 0 replyShare Rishav Kumar Singh commented Aug 18, 2018 reply Follow flag is it O(n)? 2 2 replyShare Sumit Singh Chauhan commented Aug 18, 2018 reply Follow flag How? 0 0 replyShare srestha commented Aug 18, 2018 reply Follow flag yes O(n) 0 0 replyShare Sumit Singh Chauhan commented Aug 18, 2018 reply Follow flag If we solve it, it will be like ( n + n/2 + n/4 + ........) Take n outside and the remaining series will lead to logn. so isn't the answer has to be nlogn. 0 0 replyShare Shubhgupta commented Aug 18, 2018 i edited by Shubhgupta Aug 18, 2018 reply Follow flag simply unroll the dependency.. when i=n ,j will run n times i=n/2, j will run n/2 times i=n/4, j=n/4 i=n/8,j=n/8 ----------------------- Total Complexity = n + n/2 + n/4 + n/8 .............. = n(1 + 1/2 +1/4 + 1/8............ logn times) = O(n) (1 + 1/2 +1/4 + 1/8............ logn times) this value will be nearly 1. 0 0 replyShare Sumit Singh Chauhan commented Aug 18, 2018 reply Follow flag what is the equation of log n. 0 0 replyShare Rishav Kumar Singh commented Aug 18, 2018 i edited by Rishav Kumar Singh Aug 18, 2018 reply Follow flag i think you got it 3 3 replyShare Please log in or register to add a comment.
1 1 vote in this problem ...how many times for loop will execute: first time loop: n times second time : n/2 times similarly form series = n +n/2 +n/4 + .....+1 its decreasing GP series TC = O(n) Hence option C is correct Hradesh patel answered Aug 18, 2018 Hradesh patel comment Share Follow 0 reply Please log in or register to add a comment.