Given a positive number n and precision p, find the square root of number upto p decimal places using binary search.
Note : Prerequisite : Binary search
Input : number = 50, precision = 3 Output : 7.071 Input : number = 10, precision = 4 Output : 3.1622
We have discussed how to compute integral value of square root in Square Root using Binary Search
1) As the square root of number lies in range 0 <= squareRoot <= number, therefore, initialize start and end as : start = 0, end = number.
2) Compare the square of mid integer with the given number. If it is equal to the number, then we found our integral part, else look for the same in left or right side depending upon the scenario.
3) Once we are done with finding the integral part, start computing the fractional part.
4) Initialize the increment variable by 0.1 and iteratively compute the fractional part upto p places. For each iteration, increment changes to 1/10th of it’s previous value.
5) Finally return the answer computed.
Below is the implementation of above approach :
Time Complexity : The time required to compute the integral part is O(log(number)) and constant i.e, = precision for computing the fractional part. Therefore, overall time complexity is O(log(number) + precision) which is approximately equal to O(log(number)).
- Check if a number is perfect square without finding square root
- Calculating n-th real root using binary search
- Square root of a number using log
- Find Square Root under Modulo p | Set 1 (When p is in form of 4*i + 3)
- Square root of a number without using sqrt() function
- Find Square Root under Modulo p | Set 2 (Shanks Tonelli algorithm)
- Fast method to calculate inverse square root of a floating point number in IEEE 754 format
- Find all combinations that add upto given number
- Find minimum number of Log value needed to calculate Log upto N
- Find cubic root of a number
- Find Nth positive number whose digital root is X
- Square root of an integer
- Fast inverse square root
- Babylonian method for square root
- Program to calculate Root Mean Square
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : jit_t