Find Nth root of a number using Bisection method
Given two positive integers N and P. The task is to find the Nth root of P.
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Input: P = 1234321, N = 2
Explanation: square root of 1234321 is 1111.
Input: P = 123456785, N = 20
Approach: There are various ways to solve the given problem. Here the below algorithm is based on Mathematical Concept called Bisection Method for finding roots. To find the N-th power root of a given number P we will form an equation is formed in x as ( xp – P = 0 ) and the target is to find the positive root of this equation using the Bisection Method.
How Bisection Method works?
Take an interval (a, b) such that its already known that the root is existing in that interval. After this find the mid of the interval and examine the value of function and it’s derivative at x = mid.
- If the value of function is 0 that means root is found
- If the value of the function is positive and its derivative is negative that means the root is lying in the right half.
- If the value of the function is positive and its derivative is positive that means the root is lying in the left half.
Below is the implementation of the above approach:
Time Complexity: O(log P).
Auxilliary Space: O(1).