Calculate Square Root of a Number
Given a non-negative double number, write a function to calculate its square root.
We'll cover the following...
Statement
Given a number of type double, calculate its square root.
Constraints
For this problem, the given number is always a non-negative double number.
Example
Sample input
16.0
Expected output
4.0
Try it yourself
Solution 1
We pass both low and high values to each recursive function call, where mid and square is calculated.
-
If the square of
midis equal tonthen it is the base case, and we returnmidas the square root ofn. -
If the square of
midis smaller thannthen in the next recursive call,lowis changed tomidandhighremains unchanged. -
If the square of
midis larger thannthen in the next recursive call,highis changed tomidandlowremains unchanged.
Time complexity
The time complexity of this solution is logarithmic, .
Space complexity
The space complexity of this solution is logarithmic, .
Solution 2
We can use an algorithm very similar to binary search to find the square root of a number. We know that the square root of a negative number can’t be defined without using complex numbers. As the problem is limited to non-negative numbers only, we will focus on that. It is a good idea to discuss this case with your interviewer.
Let’s assume that the given number is and we have to find its square root, . Below are two known mathematical facts.
- The square root of a number is always smaller than the given number if the number is greater than 1.
...