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. }

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

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

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

advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification 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
I’m Manish - Founder and CTO at Sanfoundry. I’ve been working in tech for over 25 years, with deep focus on Linux kernel, SAN technologies, Advanced C, Full Stack and Scalable website designs.

You can connect with me on LinkedIn, watch my Youtube Masterclasses, or join my Telegram tech discussions.

If you’re in your 20s–40s and exploring new directions in your career, I also offer mentoring. Learn more here.