![]() |
VOOZH | about |
Given a positive number n and an integer p representing the desired precision, compute the square root of n accurate to p decimal places. The solution should avoid using built-in square root functions.
Note: Precision control is required to ensure the output is correctly rounded or truncated at p digits after the decimal.
Examples:
Input: n = 50, p = 3
Output: 7.071
Explanation: The square root of 50 up to 3 decimal places is 7.071Input: n = 10, p = 4
Output: 3.1622
Explanation: The square root of 10 up to 4 decimal places is 3.1622
Table of Content
This approach begins by finding the integer part of the square root between 0 and the given number. At each step, the midpoint is checked: if its square is equal to the number, that’s the exact root; if less, the search continues on the right, and if more, it shifts to the left. Once the closest integer is found, the algorithm switches to fractional refinement. It gradually adds smaller values (like 0.1, 0.01, etc.) to approximate the square root up to the required precision.
Step by Step Approach
Finding the Integer Part using Binary Search
Decimal Precision
Final ans contains the square root of n up to p decimal places.
7.071
Time Complexity : O(log(n) + p), because binary search takes O(log n) time to find the integer part of the square root, and the refinement loop takes O(p) time to compute each of the p decimal places using linear steps.
Auxiliary Space: O(1) since it is using constant space for variables.
This approach uses binary search to approximate the square root of a number within a given decimal precision. It starts with a search range between 0 and n, repeatedly narrowing it down by comparing the square of the midpoint with n. The process stops when the range difference becomes smaller than a predefined epsilon value, which is determined by the required precision. This ensures both accuracy and efficiency in finding the result.
Step-by-Step Approach:
7.072
Time Complexity: O(log₂((n / ε))), the binary search keeps halving the search range until the difference between low and high is less than the epsilon ε (which is 10^-p for p decimal places). This gives a complexity proportional to the logarithm of (n / ε).
Auxiliary Space: O(1), only a constant number of variables (low, high, mid, eps) are used, so the extra space remains constant regardless of input size.
Note: The second approach is an alternate method as it is more concise and mathematically clean. However, due to floating-point rounding, it may give slight inaccuracies, while the first approach ensures precise digit control and matches strict output requirements.