![]() |
VOOZH | about |
Given a number N, the task is to find the floor square root of the number N without using the built-in square root function. Floor square root of a number is the greatest whole number which is less than or equal to its square root.
Examples:
Input: N = 25
Output: 5
Explanation:
Square root of 25 = 5. Therefore 5 is the greatest whole number less than equal to Square root of 25.Input: N = 30
Output: 5
Explanation:
Square root of 30 = 5.47
Therefore 5 is the greatest whole number less than equal to Square root of 30(5.47)
In the basic approach to find the floor square root of a number, find the square of numbers from 1 to N, till the square of some number K becomes greater than N. Hence the value of (K - 1) will be the floor square root of N.
Below is the algorithm to solve this problem using Naive approach:
Time Complexity: O(?N)
From the Naive approach, it is clear that the floor square root of N will lie in the range [1, N]. Hence instead of checking each number in this range, we can efficiently search the required number in this range. Therefore, the idea is to use the binary search in order to efficiently find the floor square root of the number N in log N.
Below is the recursive algorithm to solve the above problem using Binary Search:
mid = (start + end) / 2
(mid2 ? N) and ((mid + 1)2 > N)
if(mid2 ? N) updated range = [mid + 1, end]
if(mid2 > N) updated range = [low, mid - 1]
Below is the implementation of the above approach:
5
Performance Analysis: