By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,642 Members | 1,389 Online
Bytes IT Community
+ Ask a Question
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
Share this Question
Share on Google+
3 Replies


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

P: 2
Expand|Select|Wrap|Line Numbers
  1. public class recursion01 {
  2.     public static void main(String[] args){
  3.  
  4.         double base = 3;
  5.         int exp = 2;
  6.  
  7.         System.out.println(root (base,exp));
  8.  
  9.     }
  10.  
  11.     private static double root(double base, int exp) {
  12.         if (exp == 0){
  13.             return 1;
  14.         }
  15.  
  16.         else{
  17.             double sum = root(base, exp-1);
  18.             sum = sum * base;
  19.             return sum;
  20.         }
  21.     }
  22.  
  23. }
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
  1.  static double pow(double x, int n) {
  2.         if(n == 0) {
  3.             return 1;
  4.         }
  5.         return x * pow(x, n-1);
  6.     }
Then your function becomes


Expand|Select|Wrap|Line Numbers
  1.   private static double nthRoot(int n, double A) {
  2.         double x0 = 1;
  3.         boolean accurate = false;
  4.         while (!accurate) {
  5.             double x1 = (1 / (double)n) * ((n - 1) * x0 + A / pow(x0, n - 1));
  6.             accurate = accurate(x0, x1);
  7.             x0 = x1;
  8.         }
  9.         return x0;
  10.     }
  11.  
  12.  
  13.     private static boolean accurate(double x0, double x1) {
  14.         return Math.abs(x1-x0) < 0.000001;
  15.     }
Mar 13 '13 #4

Post your reply

Sign in to post your reply or Sign up for a free account.