How to find the nth Root of any positive number

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • thetechie
    New Member
    • Mar 2013
    • 2

    How to find the nth Root of any positive number

    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()?
  • r035198x
    MVP
    • Sep 2006
    • 13225

    #2
    What have you tried?

    Comment

    • thetechie
      New Member
      • Mar 2013
      • 2

      #3
      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

      • r035198x
        MVP
        • Sep 2006
        • 13225

        #4
        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

        Code:
         static double pow(double x, int n) {
                if(n == 0) {
                    return 1;
                }
                return x * pow(x, n-1);
            }
        Then your function becomes


        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

        Working...