Sqrtx
To solve this coding challenge, we need to implement a function that computes the square root of a given non-negative integer \(x\), rounded down to the nearest integer. The challenge specifies that we must not use any built-in exponent function or operator.
Explanation
We can approach this problem using the binary search algorithm. Binary search is effective here because it allows us to narrow down the potential square root quickly by halving the search space in each step. The essential idea is to find the largest integer \(m\) such that: \[ m^2 \leq x \] We will use a loop to repeatedly halve our search space based on the value of \( m^2 \) compared to \( x \). Here's the detailed step-by-step explanation of the algorithm:- Initial Check: If \( x = 0 \), then the square root is 0.
-
Binary Search Setup:
We initialize two pointers,
left
right
left
right
- Binary Search Loop:
-
Calculate
mid
left
right
-
Check if
mid * mid
-
If
mid * mid
mid
-
If `mid
mid` is less than \( x \) but \( (mid + 1)
(mid + 1) \) is greater than \( x \), return
mid
- Adjust the search range based on the comparison:
-
If
mid * mid
right
mid - 1
-
If
mid * mid
left
mid + 1
- Return Result: The loop continues until we narrow down the potential values, and we return the appropriate integer value. Below is the pseudocode implementing this logic:
-
Function Entry:
We call
mySqrt(x)
- If \(x\) is 0, return 0 immediately, because the square root of 0 is 0.
-
Initialize
left
right
x
- Binary Search Loop:
-
Calculate
mid
(left + right) // 2
-
Check if `mid
mid
is less than or equal to
, but
-
If true, return
mid
mid
x
-
If
mid * mid
x
right
mid - 1
-
If
mid * mid
x
left
mid + 1
-
Conclusion:
The loop iteratively narrows down the search space until we find the largest integer where its square is less than or equal to
x
# Function to find the square root of x, rounded down to the nearest integer
function mySqrt(x):
# Handle the edge case where x is 0
if x == 0:
return 0
# Initialize the binary search range
left = 1
right = x
# Perform binary search
while left <= right:
# Calculate the middle point
mid = (left + right) // 2
# Check if mid^2 is less than or equal to x and (mid+1)^2 is greater than x
if mid * mid <= x and (mid + 1) * (mid + 1) > x:
return mid
# If mid^2 is greater than x, adjust the right pointer
elif mid * mid > x:
right = mid - 1
# If mid^2 is less than x, adjust the left pointer
else:
left = mid + 1
# Return the result; the loop ensures we find the correct integer
return mid