1 1 vote Consider the following function int foo(int n) { int count1=0, count2=0; if (n < 0) n = -n; if (n == 0) return 1; If (n == 1) return 0; while (n) { if (n & 1) count1++; n = n >> 1; if (n & 1) count2++; n = n>>1; } return foo(abs(count1 - count2)); } What is the time complexity for the above function? Algorithms time-complexity algorithms + – Akriti sood 1.4k views answer comment Share Follow Print See all 8 Comments 8 8 Comments reply dd commented Dec 22, 2016 reply Follow flag $\begin{align*} T(n) = T\left ( \log_2 \left ( n^\frac{1}{2} \right ) \right ) + \log_4 n \end{align*}$ I found complex structure. what is the given answer ? 0 0 replyShare Akriti sood commented Dec 22, 2016 reply Follow flag it is O(log4n) actually i tried by putting n= 1024..then on evry while() iteration,it gets reduced by 1/4. so,answer is O(log 4 n) 0 0 replyShare dd commented Dec 22, 2016 reply Follow flag and forget about recursive call or what ?? :) :) :) 0 0 replyShare dd commented Dec 22, 2016 reply Follow flag but yes...recursive call is taking very small value ... 0 0 replyShare Akriti sood commented Dec 22, 2016 reply Follow flag actually at the end of while loop you will get diff between count 1 and count2 like 1 or 0 ..so it will hardly take one more fucntion call.. am i correct?? 0 0 replyShare dd commented Dec 22, 2016 reply Follow flag if the number is n = $01010101010101010101$.in binary.etc..something...abs(coont1-count2) $\approx$ $\log_2 \sqrt{n}$.. 0 0 replyShare Akriti sood commented Dec 22, 2016 reply Follow flag even if you take n= 0101010101 suppose, then after 5 iterations count1 will be 5 but count 2 will be 4 only because in last iteration,n became 0 before if (n & 1) count2++; so count2++ did nt get exceute. thn it exits while loop.and abs(count1 -count2 ) =1 0 0 replyShare dd commented Dec 22, 2016 reply Follow flag why are you incrementing count2...even after taking that sequence of bits ?? 0 0 replyShare Please log in or register to add a comment.