i am new in Java. i would like to know how to find the nth root of any positive number using recursion. Is there any way i can do this without using math.pow()?
How to find the nth Root of any positive number
Collapse
X
-
Code:public class recursion01 { public static void main(String[] args){ double base = 3; int exp = 2; System.out.println(root (base,exp)); } private static double root(double base, int exp) { if (exp == 0){ return 1; } else{ double sum = root(base, exp-1); sum = sum * base; return sum; } } }Comment
-
If you don't want to use Math.pow then you can use the general nth root algorithm x(k+1) =(1/n)*((n-1)*x(k)+A/pow(x(k),n-1)).
pow with the exponent always integer can be written recursively as
Then your function becomesCode:static double pow(double x, int n) { if(n == 0) { return 1; } return x * pow(x, n-1); }
Code:private static double nthRoot(int n, double A) { double x0 = 1; boolean accurate = false; while (!accurate) { double x1 = (1 / (double)n) * ((n - 1) * x0 + A / pow(x0, n - 1)); accurate = accurate(x0, x1); x0 = x1; } return x0; } private static boolean accurate(double x0, double x1) { return Math.abs(x1-x0) < 0.000001; }Comment
Comment