![]() |
VOOZH | about |
Given an integer X, find its square root. If X is not a perfect square, then return floor(√x). For example, if X = 11, the output should be 3, as it is the largest integer less than or equal to the square root of 11.
We can also find the floor of the square root using Python’s built-in exponentiation operator (**) and then integer conversion.
3
Explanation: x**0.5 calculates the square root of x, and int(sqrt) converts it to the largest integer less than or equal to the sqrt.
Table of Content
The same result can be obtained by using the numpy.sqrt() function to compute the square root and then applying math.floor() to round it down to the nearest integer.
3
Explanation:np.sqrt(10) function computes the square root of 10, resulting in approximately 3.162. The math.floor(sr) function then rounds it down to 3
Note: numpy.sqrt() returns a Numpy array if the input is an array, and a single value if the input is a single number.
We can also use binary search to do the same task, making it more efficient than brute-force approaches. Instead of iterating through all numbers, it repeatedly halves the search space, significantly reducing the number of calculations.
3
Explanation: If x is 0 or 1, it returns x. Otherwise, it initializes start = 1 and end = x // 2 and performs binary search. It calculates mid and checks if mid² == x. If not, it adjusts start or end accordingly, storing the closest possible square root (ans).
To find the floor of the square root, try with all-natural numbers starting from 1. Continue incrementing the number until the square of that number is greater than the given number.
4
Explanation: Increment i while i * i is ≤ x. Once i * i exceeds x, it returns i - 1 as the largest integer whose square is ≤ x.