Given an integer N and a tolerance level L, the task is to find the square root of that number using Newton's Method.
Examples:
Input: N = 16, L = 0.0001
Output: 4
42 = 16
Input: N = 327, L = 0.00001
Output: 18.0831
Newton's Method:
Let N be any number then the square root of N can be given by the formula:
root = 0.5 * (X + (N / X)) where X is any guess which can be assumed to be N or 1.
- In the above formula, X is any assumed square root of N and root is the correct square root of N.
- Tolerance limit is the maximum difference between X and root allowed.
Approach: The following steps can be followed to compute the answer:
- Assign X to the N itself.
- Now, start a loop and keep calculating the root which will surely move towards the correct square root of N.
- Check for the difference between the assumed X and calculated root, if not yet inside tolerance then update root and continue.
- If the calculated root comes inside the tolerance allowed then break out of the loop.
- Print the root.
Below is the implementation of the above approach:
Time Complexity: O(log N)
Auxiliary Space: O(1)
Recursive Approach:
- Start by defining the function findSqrt that takes three arguments - the number whose square root is to be found N, the current guess guess, and the tolerance level tolerance.
- Compute the next guess using the Newton's formula next_guess = (guess + N/guess) / 2.
- Check if the difference between the current guess and the next guess is <= tolerance level tolerance using the abs() function. If the condition is satisfied, return the next guess.
- Otherwise, recursively call the findSqrt function with the new guess.
- Last print the result
Below is the implementation of the above approach:
Time Complexity: O(log N), where N is the input number.
Auxiliary Space: O(log N)