Floor square root without using sqrt() function : Recursive
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.
Input: N = 25
Square root of 25 = 5. Therefore 5 is the greatest whole number less than equal to Square root of 25.
Input: N = 30
Square root of 25 = 5.47
Therefore 5 is the greatest whole number less than equal to Square root of 25 (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:
- Iterate a loop from numbers 1 to N in K.
- For any K, if its square becomes greater than N, then K-1 is the floor square root of N.
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:
- Implement the Binary Search in the range 0 to N.
- Find the mid value of the range using formula:
mid = (start + end) / 2
- Base Case: The recursive call will get executed till square of mid is less than or equal to N and the square of (mid+1) is greater than equal to N.
(mid2 ≤ N) and ((mid + 1)2 > N)
- If the base case is not satisfied, then the range will get changed accordingly.
- If the square of mid is less than equal to N, then the range gets updated to [mid + 1, end]
if(mid2 ≤ N) updated range = [mid + 1, end]
- If the square of mid is greater than N, then the range gets updated to [low, mid + 1]
if(mid2 > N) updated range = [low, mid - 1]
Below is the implementation of the above approach:
- Time Complexity: As in the above approach, there is Binary Search used over the search space of 0 to N which takes O(log N) time in worst case, Hence the Time Complexity will be O(log N).
- Space Complexity: As in the above approach, taking consideration of the stack space used in the recursive calls which can take O(logN) space in worst case, Hence the space complexity will be O(log N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.