Java Program to Implement Nth Root Algorithm

«
»
This is a Java Program to Implement Nth Root Algorithm. This program is used to calculate n th root of a number x.

Here is the source code of the Java Program to Implement Nth Root Algorithm. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

  1. /**
  2.  ** Java Program to implement Nth Root Algorithm
  3.  **/
  4.  
  5. import java.util.Scanner;
  6.  
  7. /** Class NthRoot **/
  8. public class NthRoot
  9. {
  10.     public double nthroot(int n, double x) 
  11.     {
  12.         return nthroot(n, x, .0001);
  13.     }
  14.     public double nthroot(int n, double x, double p) 
  15.     {
  16.         if(x < 0) 
  17.         {
  18.             System.err.println("Negative!");
  19.             return -1;
  20.         }
  21.         if(x == 0) 
  22.             return 0;
  23.         double x1 = x;
  24.         double x2 = x / n;  
  25.         while (Math.abs(x1 - x2) > p) 
  26.         {
  27.             x1 = x2;
  28.             x2 = ((n - 1.0) * x2 + x / Math.pow(x2, n - 1.0)) / n;
  29.         }
  30.         return x2;
  31.     }
  32.     /** Main **/
  33.     public static void main(String[] args)
  34.     {
  35.         Scanner scan = new Scanner(System.in);
  36.         System.out.println("Nth Root Algorithm Test\n");
  37.         System.out.println("Enter n and x");
  38.         int n = scan.nextInt();
  39.         double x = scan.nextInt();
  40.         NthRoot nr = new NthRoot();
  41.         double root = nr.nthroot(n, x);
  42.         System.out.println("\nRoot = "+ root);
  43.     }    
  44. }

advertisement
Nth Root Algorithm Test
 
Enter n and x
2
3
 
Root = 1.7320508100147274

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

advertisement
advertisement
If you wish to look at all Java Programming examples, go to Java Programs.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.