Search code examples
algorithmtime-complexityspace-complexity

How to know the time and space complexity of the following snapshot?


I understand how the code in the following snapshot works but I am curious how would I know the time and space complexity of it?

I know it depends on the time it takes for 'b' to become zero. Is there some mathematical way that I can find this? I understand that this wont go into millions of recursions ever. But still was curious of how many recursions would happen?

Question: Add 2 numbers without using any arithmetic operations- enter image description here


Solution

  • Since carry is a&b shifted left, its bit-0 (least significant bit or LSB) is zero. Also, carry will have zero in each position p where b had zero in position p-1. This means that in the first recursive call, b will have a zero bit-0, and in the second recursive call, it will have zero in bit-0 and bit-1 (2 LSBs are zero), and so on. In the n-th recursive call, b will have n LSBs that are 0, so when n is the position of the most significant non-zero bit in a, carry will be zero, and the recursion will end in the next call.

    So the time complexity is O(n), where n is the number of bits in a (more accurately, the position of the most significant non-zero bit in a, which in the worst case would be the number of bits in a). The space complexity is also O(n) because there are n recursive calls, but since this is tail recursion, it could be optimized away, so the optimized space complexity would be O(1).