Exercise 1: Integer square root of an integer
You need to write a function, nsqrt(), that takes as input an integer x, and return the largest integer that does not exceed 𝑥⎯⎯√ . You need to abide by the following constraints:
The time complexity of your algorithm should be 𝑂(log𝑥) .
You cannot use sqrt() function.
For example, nsqrt(11) = 3, and nsqrt(1369) = 37.
- binary search:
def nsqrt(x): # do not change the heading of the function
left = 1
right = x
while (left <= right):
mid = (left + right) // 2
if mid > x // mid: # if x < mid^2, go to left side
right = mid - 1
else: # otherwise go to right side
left = mid + 1
return right # if left