- Why does the code not work if we include a third condition in the while loop i.e. return mid if mid_squared = k? For example:
def square_root(k):
left = 0
right = k
while left < right:
mid = (left + right)//2
mid_squared = mid*mid
if mid_squared < k:
left = mid + 1
elif mid_squared > k:
right = mid - 1
else: ##mid_squared = k
return mid
return left - 1
for example, if k= 4, we begin with [0,4]. mid = 2, so we could simply return mid directly.
- Also, in each iteration, we are either move left to mid + 1 or right to mid - 1. I noticed that the code fails if we move left and right to mid, instead of mid + 1 and mid - 1, respectively. Could you throw some light on why this approach will not work?
Thanks!