Find Nth root of a number using Bisection method | Java program for the above approach ; Function that returns the value of the function at a given value of x ; calculating the value of the differential of the function ; The function that returns the root of given number ; Defining range on which answer can be found ; finding mid value ; Driver code
import java . util . * ; class GFG { static double f ( double x , int p , double num ) { return Math . pow ( x , p ) - num ; } static double f_prime ( double x , int p ) { return p * Math . pow ( x , p - 1 ) ; } static double root ( double num , int p ) { double left = - num ; double right = num ; double x ; while ( true ) { x = ( left + right ) / 2.0 ; double value = f ( x , p , num ) ; double prime = f_prime ( x , p ) ; if ( value * prime <= 0 ) left = x ; else right = x ; if ( value < 0.000001 && value >= 0 ) { return x ; } } } public static void main ( String args [ ] ) { double P = 1234321 ; int N = 2 ; double ans = root ( P , N ) ; System . out . print ( ans ) ; } }