Well, you noticed that you can divide your function into 3 separate cases and already determined that the first 2 are O (1). The third is a bit more complicated, but you can split it into two parts.
Recursion obviously comes from:
g(n//2)*g(n%2)
We can immediately see that n%2 will evaluate either 0 or 1, which again will resolve one of the first 2 cases, so we can ignore this. Leaving us with g(n//2) . Rewriting this as a print loop and looking at the output, you will notice something:
>>> n = 37 >>> while n > 1: ... n //= 2 ... print(n) ... 18 9 4 2 1
As you can see, the terms are halved every time, and this happens in recursion. This is logarithmic.
As a result, the worst case for this function is O (logn).
You can learn more about what logn really means in Big-O notation by looking at this question .
source share