454,642 Members | 1,389 Online Need help? Post your question and get tips & solutions from a community of 454,642 IT Pros & Developers. It's quick & easy.

# How to find the nth Root of any positive number

 P: 2 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()? Mar 13 '13 #1
3 Replies

 10K+ P: 13,264 What have you tried? Mar 13 '13 #2

 P: 2 Expand|Select|Wrap|Line Numbers 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;         }     }   } Mar 13 '13 #3

 10K+ P: 13,264 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 Expand|Select|Wrap|Line Numbers  static double pow(double x, int n) {         if(n == 0) {             return 1;         }         return x * pow(x, n-1);     } Then your function becomes Expand|Select|Wrap|Line Numbers   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;     } Mar 13 '13 #4 